在Javascript/Lodash中更新对象数组中的单个对象字段
是否有方法更新对象数组中对象中的单个字段在Javascript/Lodash中更新对象数组中的单个对象字段,javascript,arrays,filter,lodash,Javascript,Arrays,Filter,Lodash,是否有方法更新对象数组中对象中的单个字段 PeopleList= [ {id:1, name:"Mary", active:false}, {id:2, name:"John", active:false}, {id:3, name:"Ben", active:true}] 例如,将John的active设置为true 我尝试在Lodash中执行此操作,但没有返回正确的结果。它返回一个lodash包装 updatedList = _.chain(Peopl
PeopleList= [
{id:1, name:"Mary", active:false},
{id:2, name:"John", active:false},
{id:3, name:"Ben", active:true}]
例如,将John的active设置为true
我尝试在Lodash中执行此操作,但没有返回正确的结果。它返回一个lodash包装
updatedList = _.chain(PeopleList)
.find({name:"John"})
.merge({active: true});
.find(PeopleList,{name:'John'}).active=true
您甚至不需要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;
}
或者如果你不想改变原来的列表
const newList = PeopleList.map(people => {
if(people.name === "John") {
return {...people, active: true};
}
return {...people};
});
我认为Lodash对初学者来说更好,所以他们不必处理透明化。