使用扩展运算符更新包含对象的数组 [英] Update Array containing objects using spread operator

查看:17
本文介绍了使用扩展运算符更新包含对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 javascript/typescript 对象的数组.

I have an array containing objects in javascript / typescript.

let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]

如何更新第二个元素的名称(id 为 2)并使用 javascript spread (...) 运算符将数组复制到新数组?

How can I update name of the second element (with id 2) and copy the array to a new array using javascript spread (...) operator?

推荐答案

您可以混合使用 .map... 扩展运算符

You can use a mix of .map and the ... spread operator

您可以在创建新数组后设置值

You can set the value after you've created your new array

let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}];

let array2 = array.map(a => {return {...a}})

array2.find(a => a.id == 2).name = "Not Two";

console.log(array);
console.log(array2);

.as-console-wrapper { max-height: 100% !important; top: 0; }

或者你可以在.map

let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}];

let array2 = array.map(a => {
  var returnValue = {...a};

  if (a.id == 2) {
    returnValue.name = "Not Two";
  }

  return returnValue
})


console.log(array);
console.log(array2);

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于使用扩展运算符更新包含对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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