如何转换这种数据格式?
头一次遇到 惭愧 竟然懵逼了无从下手。求大佬指点
var dataA = [{ cid: 125, name: 'y1' },
{ cid: 845, name: 'y2' },
{ cid: 956, name: 'y3' },
{ cid: 634, name: 'y4' },
]
var dataB = [
{ uid: 984, name: 'x1' },
{ uid: 9634, name: 'x2' },
{ uid: 6574, name: 'x3' },
{ uid: 39764, name: 'x4' },
{ uid: 3164, name: 'x5' },
{ uid: 7421, name: 'x6' },
]
var dataC = [
{ id: 1245, cid: 125, uid: 984 },
{ id: 1237, cid: 845, uid: 3164 }
]
//期待数据 将上述三条数据转换成 如下
var corssData = [
[
'y1',
{ cid: 125, uid: 984, id: 1245, exist: true },
{ cid: 125, uid: 9634, id: null, exist: false },
{ cid: 125, uid: 6574, id: null, exist: false },
{ cid: 125, uid: 39764, id: null, exist: false },
{ cid: 125, uid: 3164, id: null, exist: false },
{ cid: 125, uid: 7412, id: null, exist: false },
],
[
'y2',
{ cid: 845, uid: 984, id: null, exist: false },
{ uid: 9634, cid: 125, id: null, exist: false },
//...诸如此类
],
// ...诸如此类
]
回答
var corssData = dataA.map(iA => { return [iA.name, ...dataB.map(iB => {
var c = dataC.find(iC => iC.cid === iA.cid && iC.uid === iB.uid)
return {
cid: iA.cid, uid: iB.uid, id: c && c.id, exist: !!c
}
})]
})
demo一个,写法上还可以再优化:
var A = [ { cid: 125, name: 'y1' },
{ cid: 845, name: 'y2' },
{ cid: 956, name: 'y3' },
{ cid: 634, name: 'y4' },
]
var B = [
{ uid: 984, name: 'x1' },
{ uid: 9634, name: 'x2' },
{ uid: 6574, name: 'x3' },
{ uid: 39764, name: 'x4' },
{ uid: 3164, name: 'x5' },
{ uid: 7421, name: 'x6' },
]
var C = [
{ id: 1245, cid: 125, uid: 984 },
{ id: 1237, cid: 845, uid: 3164 },
]
var corssData = []
function FunctionName (dataA, dataB, dataC) {
dataA.forEach(function (item, index) {
var array = []
array.push(item.name)
array.push(dataB.map(function (itemB, indexB) {
var id = null
var exist = false
for (var i = 0; i < dataC.length; i++) {
if (dataC[i].cid === item.cid && dataC[i].uid === itemB.uid) {
id = dataC[i].id
exist = true
}
}
return {
cid: item.cid,
uid: itemB.uid,
id: id,
exist: exist,
}
}))
corssData.push(array)
})
}
FunctionName(A, B, C)
console.log(corssData)
以上是 如何转换这种数据格式? 的全部内容, 来源链接: utcz.com/a/41030.html