1

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?

1
  • 1
    "is that correct" No. .map will create a new array, but obj.age= newage will still mutate the object. .map already existed before ES6 btw. Commented Mar 8, 2017 at 0:03

1 Answer 1

2

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

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.