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.
I tried to do this in Lodash but it doesn't return a proper result. It returns a lodash wrapper.
        updatedList = _.chain(PeopleList)
       .find({name:"John"})
       .merge({active: true});
                _.find(PeopleList, { name: 'John' }).active = true
Well you don't even need lodash for this with 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};
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With