如何根据内部数组的更改属性值进行部分深度合并



我正在尝试根据另一个关联的更改值数组更新对象值数组。 初始数组:

const primaryArray = [
{ 
name: 'Product Family 1',
products: [ {name: 'product 1', selected: false}, {name: 'product 2', selected: false}
]},
{ 
name: 'Product Family 2',
products: [ {name: 'product 3', selected: false}, {name: 'product 4', selected: false}
]},
];

更新项的数组:

const updates = [
{ 
name: 'Product Family 1',
products: [ {name: 'product 2', selected: true}]
},
{ 
name: 'Product Family 2',
products: [ {name: 'product 4', selected: true}]
},
];

实质上,只有更新数组中列出的产品应该在主阵列中更改,同时仍保留现有的未更改产品

我已经在 Object.assign 和 _.merge 上尝试了多种变体,由于 primaryArray 与"更新"数组中的元素数量不同,因此它们都没有按预期工作,例如:

const newArray = primaryArray.forEach(obj => {
return (updates.find(o => o.name === obj.name) || obj);
});

我还尝试了将.map结合使用.find和.forEach的多种变体,但没有任何运气。

预期结果应为:

const newArray = [
{ 
name: 'Product Family 1',
products: [ {name: 'product 1', selected: false}, {name: 'product 2', selected: true}
]},
{ 
name: 'Product Family 2',
products: [ {name: 'product 3', selected: false}, {name: 'product 4', selected: true}
]},
....
// where the new Array will also inherit all other objects from the primaryArray
name: 'Product Family 102',
products: [ {name: 'product 1000', selected: false}
]},
];

我会先updates变成一个哈希表:

const updateByName = {};
for(const { name, products } of updates)
for(const {name: inner, selected } of products)
updateByName[name + " > " + inner] = selected;

更新非常简单:

const result = primaryArray.map(({ name, products }) => ({
name,
products: products.map(({ name: inner, selected }) => {
const update = updateByName[name + " > " + inner];
return {
name: inner,
selected: update !== undefined ? update : selected,
};
})),
}));

对于即将推出的零合并运算符,这将稍微优雅一些。

最新更新