使用es6映射基于属性值更新对象数组 [英] update array of object base on property value using es6 map

查看:1177
本文介绍了使用es6映射基于属性值更新对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个对象数组

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

如何将爱丽丝的年龄更新为11岁?

How can I update Alice's age to 11?

我尝试使用es6的地图

I tried using map of es6

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

我映射而不是普通的for循环的原因是我不想变异原始人对象,对吗?

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?

推荐答案

问题在于,当您使用Array.map循环遍历数组时,访问并更新年龄的对象仍然是原始对象,并按了与Array.map创建的新数组完全相同的对象.

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

这篇关于使用es6映射基于属性值更新对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆