使用另一个数组更新对象数组

Update an array of objects using another array

我需要根据 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 是否在对象内部会更快(与检查数组内部相比)。但实际上在大多数情况下你应该不会注意到差异。

试试这个,使用包含函数的映射函数。希望这个答案能给出您的实际结果。如果没有那么评论给我,我会给你另一个答案。

const found = a.map(function(mapData){
    (marked.includes(mapData.id)) ? mapData.active = true : '';
    return mapData;
})

这实际上只是@Giorgi Moniava 的回答的扩展,因为问题已经更新。我认为您应该将他的回答标记为已接受的回答。基本上您需要做的就是检查 active 的值是真还是假。如果为真,则将状态设置为 updated 否则,将状态设置为空字符串。

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 result = a.map(obj => {
    const isActive = marked.includes(obj.id);
    const status = isActive ? 'updated' : '';
    return {
      ...obj,
      active: isActive,
      status: status
    }
})
console.log(result)