简体   繁体   English

在Javascript / Lodash中更新对象数组中的单个对象字段

[英]Update a Single Field of Object in Object Array in Javascript/Lodash

Is there a way to update a single field in an object within an array of objects? 有没有办法更新对象数组中对象的单个字段?

PeopleList= [
   {id:1, name:"Mary", active:false}, 
   {id:2, name:"John", active:false}, 
   {id:3, name:"Ben", active:true}]

For instance, setting John's active to true. 例如,将John的active设置为true。

I tried to do this in Lodash but it doesn't return a proper result. 我试图在Lodash中这样做,但它没有返回正确的结果。 It returns a lodash wrapper. 它返回一个lodash包装器。

        updatedList = _.chain(PeopleList)
       .find({name:"John"})
       .merge({active: true});

Well you don't even need lodash for this with es6: 嗯,你甚至不需要lodash与es6:

PeopleList.find(people => people.name === "John").active = true;
//if the record might not exist, then
const john = PeopleList.find(people => people.name === "John")
if(john){
  john.active = true;
}

Or if you don't want to mutate the original list 或者,如果您不想改变原始列表

const newList = PeopleList.map(people => {
  if(people.name === "John") {
    return {...people, active: true};
  }
  return {...people};
});

_.find(PeopleList, { name: 'John' }).active = true

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

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