简体   繁体   English

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

[英]Update an array of objects using another array

i need to update the array of objects based on another array in ES6.我需要根据 ES6 中的另一个数组更新对象数组。 Example例子

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:"" },
]

my second array which contain the objects我的第二个包含对象的数组

let marked = [167,33,23];

expected results as below预期结果如下

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:"" },
]

please let me know how to get as expected result.请让我知道如何获得预期的结果。 do we have any other methods in lodash for this.?我们在 lodash 中还有其他方法吗?

This is really just an extension of @Giorgi Moniava's answer since the question has been updated.由于问题已更新,这实际上只是@Giorgi Moniava 答案的扩展。 I think you should mark his answer as the accepted one.我认为您应该将他的答案标记为已接受的答案。 Basically all you need to do is check if the value for active is true or false.基本上你需要做的就是检查active的值是真还是假。 If it's true, set the status to updated otherwise, set the status to an empty string.如果为真,则将状态设置为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)

You don't need lodash, you could do this:你不需要 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)

You can make this faster if you go over the marked array and store its elements in an object.如果您遍历marked数组并将其元素存储在对象中,则可以加快速度。 Then during the map checking if element x.id is inside the object will be faster (vs checking inside array).然后在map检查期间元素x.id是否在对象内部会更快(与检查数组内部相比)。 But in practice in most of the cases you should not notice the difference.但实际上,在大多数情况下,您不应该注意到差异。

Try with this, use map function with includes function.试试这个,使用带有包含功能的地图功能。 Hope so this answer gives your actual result.希望这个答案能给出你的实际结果。 if not then comment to me I'll give you another answer.如果没有,请给我评论,我会给你另一个答案。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM