arr1 = [
{uid:"111111",name:"test1"},
{uid:"222222",name:"test2"},
{uid:"333333",name:"test3"},
{uid:"444444",name:"test4"},
{uid:"555555",name:"test5"},
]
arr2 = [
{uid:"111111", score:100},
{uid:"222222", score:80},
{uid:"333333", score:85},
{uid:"444444", score:95},
]
想要合并成一个新的数组,uid没有分数据用0填充,如何在小程序的 js里面实现?
实现结果:
arr3 = [
{name:"test1",score:100},
{name:"test2",score:80},
{name:"test3",score:85},
{name:"test4",score:95},
{name:"test5",score:0},
]
_arr2 = arr2.reduce((t, {uid,score}) => (t[uid] = score, t), {}); arr3 = arr1.map(({uid,name}) => ({name,score: _arr2[uid] || 0})); console.info(arr3);
生并。
随手写的,自己排错去。
let obj3 = {} arr1.forEach(v=>obj[v.uid].name=v.name) arr2.forEach(v=>obj[v.uid].score=v.score) let arr3=[] for(let k in obj3) { arr3.push({ uid:k, name:obj3[k].name, score:obj3[k].score }) }
最暴力的,双重循环一个个找,找到的每一对构造一个临时对象,对象push进arr3里面。
用代码实现啊,就自己写呗😂
两次遍历