在我的代码中,我有两个数组,第一个数组包含多个对象。第二个是存储序列化表单数据(映射到 JSON)。所以两个数组都有相同的键。
我想要实现的是根据新数组中对象的值,通过对象中的 ID 动态更新原始数组中对象的值。
在网上找到了一些示例,但很难让它们发挥作用。因为它们中的大多数都显示任一级别的对象,但我正在处理数组中的复杂嵌套对象。
var products = [
{
Id: 1,
Name: 'Product1',
Attributes: {
Storage: 'Normal',
Size: 'Small'
}
},
{
Id: 2,
Name: 'Product2',
Attributes: {
Storage: 'Normal',
Size: 'Small'
}
}
];
var newData = [
{
Id: 2,
Name: 'French Fries'
},
{
Id: 1,
Attributes: {
Size: 'Medium'
}
}
];
预期结果是 products
数组现在使用第二个数组中的值进行更新。
Output:
[
{
Id: 1,
Name: 'Product1',
Attributes: {
Storage: 'Normal',
Size: 'Medium'
}
},
{
Id: 2,
Name: 'French Fries',
Attributes: {
Storage: 'Normal',
Size: 'Small'
}
}
]
最佳答案
您可以选择 Map
更新项目并迭代产品
。
如果找到要更新的项目,则采用递归方法并迭代这些条目并检查该值是否为对象,然后迭代嵌套属性。
如果没有找到嵌套对象,则更新属性。
这也适用于数组。
function update(target, source) {
Object.entries(source).forEach(([key, value]) => {
if (value && typeof value === 'object') {
update(target[key] = target[key] || (Array.isArray(value) ? [] : {}), value);
} else if (target[key] !== value) {
target[key] = value;
}
});
}
var products = [{ Id: 1, Name: 'Product1', Attributes: { Storage: 'Normal', Size: 'Small' } }, { Id: 2, Name: 'Product2', Attributes: { Storage: 'Normal', Size: 'Small' } }],
newData = [{ Id: 2, Name: 'French Fries' }, { Id: 1, Attributes: { Size: 'Medium' } }],
map = new Map(newData.map(o => [o.Id, o]));
products.forEach(o => map.has(o.Id) && update(o, map.get(o.Id)));
console.log(products);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 从数组中的另一个对象更新数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55757916/