我有两个对象数组:
array1 = [{"id":1,"cost":200,"qty":56},{"id":2,"cost":100,"qty":16}];
array2 = [{"id":1,"cost":200,"desc":"a good one"},{"id":2,"cost":100,"desc":"a bad one"},{"id":3,"cost":50,"desc":"an okay one"}];
我想把它们合并成这样:
[{"id":1,"cost":200,"qty":56,"desc":"a good one"},{"id":2,"cost":100,"qty":16,"desc":"a bad one"}];
请注意,新数组具有两个数组的属性,但它忽略了第一个数组中不存在的对象。
我试过了:
var mergethem = function() {
var array1 = [{"id":1,"cost":200,"qty":56},{"id":2,"cost":100,"qty":16}];
var array2 = [{"id":1,"cost":200,"desc":"a good one"},{"id":2,"cost":100,"desc":"a bad one"},{"id":3,"cost":50,"desc":"an okay one"}];
var newarray= array2.filter(i => array1.map(a=> { if(a.id == i.id) i.qty = a.qty; return i; }));
return newarray.filter(i=> { if(i.qty) return i; });
}
console.log(mergethem());
这似乎有时工作,有时它不取决于环境。我不知道问题出在哪里,所以我想请别人试一下。
您可以获取第二个数组对象的引用并映射第一个数组,同时添加第二个数组的属性(如果存在)
const
array1 = [{ id: 1, cost: 200, qty: 56 }, { id: 2, cost: 100, qty: 16 }],
array2 = [{ id: 1, cost: 200, desc: "a good one" }, { id: 2, cost: 100, desc: "a bad one" }, { id: 3, cost: 50, desc: "an okay one" }],
references2 = Object.fromEntries(array2.map(o => [o.id, o])),
result = array1.map(o => ({ ...o, ...references2[o.id] }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
const array1 = [
{"id":1,"cost":200,"qty":56},
{"id":2,"cost":100,"qty":16}
];
const array2 = [
{"id":1,"cost":200,"desc":"a good one"},
{"id":2,"cost":100,"desc":"a bad one"},
{"id":3,"cost":50,"desc":"an okay one"}
];
const result = array1.reduce((previousValue, currentValue) => {
const needObj = array2.find(o => o.id === currentValue.id) ?? {};
previousValue.push({...currentValue, ...needObj});
return previousValue;
}, []);
console.log(result);