我有2个数组,我想要一个基于条件的新数组,这两个数组的内容匹配
arr1 = [{
package_id: 'aabbccdd',
level: 2
},
{
package_id: 'xycd21',
level: 3
}
]
arr2 = [{
package_id: 'aabbccdd',
level: 1
},
{
package_id: 'zcb21',
level: 5
}]
mergedArray = [{
package_id: 'aabbccdd',
arr1Level: 2,
arr2Level: 1
},
{
package_id: 'xycd21',
arr1Level: 3,
arr2Level: 0
},
{
package_id: 'zcb21',
arr1Level: 0,
arr2Level: 5
}]
因此,如果要在两个数组中检查package_id。如果在任一数组中找到,则新数组推送一个元素,其中两个数组中的级别针对package_id提及。
我无法弄清楚这样做的逻辑。如果可以通过lodash完成,请告诉我。
答案 0 :(得分:1)
你可以像我在这里使用循环一样轻松解决这个问题:
var arr1 = [{
package_id: 'aabbccdd',
level: 2
},
{
package_id: 'xycd21',
level: 3
}
];
var arr2 = [{
package_id: 'aabbccdd',
level: 1
},
{
package_id: 'zcb21',
level: 5
}
];
var mergedArr = [];
var tempObj = {};
for(var i = 0; i < arr1.length; i++){
tempObj.package_id = arr1[i].package_id;
tempObj.arr1Level = arr1[i].level;
tempObj.arr2Level = 0;
for(var k = 0; k < arr2.length; k++){
if(arr1[i].package_id === arr2[k].package_id){
tempObj.arr2Level = arr2[k].level;
}
}
mergedArr.push(tempObj);
tempObj = {};
}
for(i = 0; i < arr2.length; i++){
var isNew = true;
for(k = 0; k < mergedArr.length; k++){
if(arr2[i].package_id === mergedArr[k].package_id){
isNew = false;
}
}
if(isNew){
tempObj.package_id = arr2[i].package_id;
tempObj.arr2Level = arr2[i].level;
tempObj.arr1Level = 0;
mergedArr.push(tempObj);
tempObj = {};
}
}
console.log(mergedArr);
答案 1 :(得分:1)
您可以先将两个数组添加到一个数组中,然后使用reduce()
和forEach()
创建新的对象数组。您还可以使用其他对象按package_id
var arr1 = [{ package_id: 'aabbccdd', level: 2 }, { package_id: 'xycd21', level: 3 }];
var arr2 = [{ package_id: 'aabbccdd', level: 1 }, { package_id: 'zcb21', level: 5 }];
var o = {}
var arrays = [arr1, arr2]
var keys = Array.from(Array(arrays.length), (e, i) => ({['arr' + (i + 1) + 'Level']: 0}))
var result = arrays.reduce(function(r, a, i) {
a.forEach(function(e) {
if (!o[e.package_id]) {
o[e.package_id] = Object.assign({}, {package_id: e.package_id}, ...keys)
r.push(o[e.package_id]);
}
o[e.package_id]['arr' + (i + 1) + 'Level'] = e.level;
})
return r;
}, [])
console.log(result)
答案 2 :(得分:0)
您可以为不同的数组使用动态键的结构方法,并使用键作为生成默认值的帮助。
var arr1 = [{ package_id: 'aabbccdd', level: 2 }, { package_id: 'xycd21', level: 3 }],
arr2 = [{ package_id: 'aabbccdd', level: 1 }, { package_id: 'zcb21', level: 5 }],
keys = [{ level: 'arr1level' }, { level: 'arr2level' }],
result = [arr1, arr2].reduce(function (hash) {
return function (r, a, i) {
a.forEach(function (b) {
if (!hash[b.package_id]) {
hash[b.package_id] = { package_id: b.package_id },
r.push(hash[b.package_id]);
}
keys.forEach(function (key) {
Object.keys(key).forEach(function (k) {
hash[b.package_id][key[k]] = 0;
});
});
Object.keys(b).forEach(function (k) {
var key = keys[i][k] || k;
hash[b.package_id][key] = b[k];
});
});
return r;
};
}(Object.create(null)), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }