Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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});
like image 495
lost9123193 Avatar asked Feb 23 '17 06:02

lost9123193


2 Answers

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

like image 132
bcherny Avatar answered Oct 05 '22 20:10

bcherny


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};
});
like image 36
cubbuk Avatar answered Oct 05 '22 22:10

cubbuk