10

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});

2 Answers 2

20

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};
});
Sign up to request clarification or add additional context in comments.

1 Comment

I think Lodash is better for a beginner, so they don't have to deal with transpilation.
13

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.