我需要根据 ES6 中的另一个数组来更新对象数组。 示例
let a = [
{ id : 23, active :false, status:"" },
{ id : 33, active :false, status:"" },
{ id : 167, active :false, status:"" },
{ id : 18, active :false, status:"" },
{ id : 200, active :false, status:"" },
]
我的第二个包含对象的数组
let marked = [167,33,23];
预期结果如下
let a = [
{ id : 23, active :true, status:"updated"},
{ id : 33, active :true, status:"updated" },
{ id : 167, active :true, status:"updated" },
{ id : 18, active :false, status:"" },
{ id : 200, active :false, status:"" },
]
请告诉我如何获得预期的结果。我们在 lodash 中还有其他方法吗?
最佳答案
你不需要lodash,你可以这样做:
let a = [{
id: 23,
active: false
},
{
id: 33,
active: false
},
{
id: 167,
active: false
},
{
id: 18,
active: false
},
{
id: 2,
active: false
},
]
let marked = [167, 33, 23];
let result = a.map(x => ({
...x,
active: marked.includes(x.id)
}))
console.log(result)
如果您遍历 marked
数组并将其元素存储在一个对象中,您可以加快速度。然后在 map
期间检查元素 x.id
是否在对象内部会更快(与检查数组内部相比)。但实际上,在大多数情况下,您应该不会注意到差异。
关于javascript - 使用另一个数组更新对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69691275/