1

I have an array of person objects and I want to update one of object in place.

persons: [{
    id: '1',
    name: 'John',
    age: 12
    }, {
    id: '2',
    name: 'Tom',
    age: 13
    }, {
    id: '3',
    name: 'David',
    age: 14
}]

The function I have is:

function updatePersonsWith(id, propName, value) {
   this.persons.???
}

The arguments passed are id of the person I want to update, propName is the properties of person object, can be id, name or age, value is the value I want to replace with.

I want to find an object by it's id and update only this object of the array.

updatePersonsWith(2, age, 16)

The result would be:

persons: [{
    id: '1',
    name: 'John',
    age: 12
    }, {
    id: '2',
    name: 'Tom',
    age: 16
    }, {
    id: '3',
    name: 'David',
    age: 14
}]

Could be ES6 or using lodash.

1

3 Answers 3

5

Try:

let person = this.persons.find((person) => {
   return person.id === id;
});

if (person && person[propName]) {
 person[propName] = value;
}

Working example:

var persons = [{
    id: '1',
    name: 'John',
    age: 12
    }, {
    id: '2',
    name: 'Tom',
    age: 13
    }, {
    id: '3',
    name: 'David',
    age: 14
}];

function update(id, prop, val) {
	var person = persons.find(function(p) {
  	return p.id === id;
  });
  
  if (person && person[prop]) {
  	person[prop] = val;
  }
}

update('1', 'age', 77);

console.log(persons[0].age);

Sign up to request clarification or add additional context in comments.

Comments

4

You can use this:

let persons =  [{
    id: '1',
    name: 'John',
    age: 12
    }, {
    id: '2',
    name: 'Tom',
    age: 13
    }, {
    id: '3',
    name: 'David',
    age: 14
}];


function updatePersonsWith(id, propName, value) {
   let item = persons.find((v) => {
      return v.id == id;
   });
   if (item && item.hasOwnProperty(propName)) {
      item[propName] = value;
   }
};

updatePersonsWith(2, 'age', 16);
console.log(persons)

Comments

1

Using lodash, you can do like,

function updatePersonsWith(id, propName, value) {
  var match = _.find(persons , function(person) { return person.id === id });
  if(match)
      match[propName] = value;
}

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.