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

时间:2017-02-23 06:21:57

标签: javascript arrays filter lodash

有没有办法更新对象数组中对象的单个字段?

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

例如,将John的活动设置为true。

我试图在Lodash中这样做,但它没有返回正确的结果。它返回一个lodash包装器。

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

对于es6:

,你甚至不需要lodash
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;
}

或者,如果您不想改变原始列表

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