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

los*_*193 3 javascript arrays filter lodash

有没有一种方法来更新对象数组中的一个对象中的单个字段?

PeopleList= [
   {id:1, name:"Mary", active:false}, 
   {id:2, name:"John", active:false}, 
   {id:3, name:"Ben", active:true}]
Run Code Online (Sandbox Code Playgroud)

例如,将John的active设置为true。

我尝试在Lodash中执行此操作,但未返回正确的结果。它返回一个lodash包装器。

        updatedList = _.chain(PeopleList)
       .find({name:"John"})
       .merge({active: true});
Run Code Online (Sandbox Code Playgroud)

bch*_*rny 10

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


cub*_*buk 9

嗯,您甚至不需要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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 我认为 Lodash 更适合初学者,所以他们不必处理转译。 (2认同)