简体   繁体   中英

update array of object base on property value using es6 map

I have this array of object

[
  {
    "name": "Alice",
    "age": 10
  },
  {
    "name": "Samantha",
    "age": 20
  },
  {
    "name": "Mary",
    "age": 19
  }
]

How can I update Alice's age to 11?

I tried using map of es6

const newage = 11;
 const newDate = person.map(obj => 
      return 'Alice' === obj.name ? obj.age= newage : obj
    )

The reason why I map instead of normal for loop is that I do not want to mutate the origin person object, is that correct?

The problem is that as you loop through the array with Array.map , the objects you access and update the age with are still the originals, and you push the exact same objects to the new array that Array.map creates.

So an intuitive way to fix this, is to clone new objects and update the new objects. I made a example for you so you can see the outcome.

const original = [
  {"name": "Alice","age": 10},
  {"name": "Samantha","age": 20},
  {"name": "Mary","age": 19}
];
const newage = 11;
const newData = original.map(obj => {
  // clone the current object
  const newObj = Object.assign({}, obj);
  // update the new object
  if (newObj.name === 'Alice') newObj.age = newage;
  return newObj;
});

If you want your original array to remain unchanged and make a new array with the updated objects try the following:

 var person = [ { "name": "Alice", "age": 10 }, { "name": "Samantha", "age": 20 }, { "name": "Mary", "age": 19 } ]; const newage = 11; var newPerson = []; for (var i = 0; i<person.length; i++){ var ageVal = person[i].name == 'Alice' ? newage : person[i].age; newPerson.push({name: person[i].name, age: ageVal}); } console.log('Original person object:'); console.log(person); console.log('Modified newPerson object:'); console.log(newPerson); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM