首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用spread运算符更新包含对象的数组

使用spread运算符更新包含对象的数组
EN

Stack Overflow用户
提问于 2017-06-13 14:16:48
回答 9查看 65.7K关注 0票数 35

我有一个数组,其中包含javascript / typescript中的对象。

代码语言:javascript
运行
复制
let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]

如何更新第二个元素的名称(使用id 2)并使用javascript (.)将数组复制到新数组接线员?

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2017-06-13 14:33:44

您可以使用.map spread operator的混合

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

代码语言:javascript
运行
复制
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);
代码语言:javascript
运行
复制
.as-console-wrapper { max-height: 100% !important; top: 0; }

您可以在.map中这样做

代码语言:javascript
运行
复制
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);
代码语言:javascript
运行
复制
.as-console-wrapper { max-height: 100% !important; top: 0; }

票数 46
EN

Stack Overflow用户

发布于 2017-06-13 14:40:16

有几种方法可以做到这一点。我建议使用Array.map

代码语言:javascript
运行
复制
let new_array = array.map(element => element.id == 2 ? {...element, name : 'New Name'} : element);

或者使用Object.assign

代码语言:javascript
运行
复制
let new_array = array.map(element => element.id == 2 ? Object.assign({}, element, {name : 'New Name'}) : element);

Map返回一个新数组,因此不需要数组扩展操作符。

票数 3
EN

Stack Overflow用户

发布于 2022-06-24 11:53:49

使用Spred运算符,可以使用以下方法更新特定的数组值

代码语言:javascript
运行
复制
let array = [
  { id: 1, name: "One" },
  { id: 2, name: "Two" },
  { id: 3, name: "Three" },
];
const label = "name";
const newValue = "Two Updated";
// Errow comes if index was string, so make sure it was integer
const index = 1; // second element, 

const updatedArray = [
  ...array.slice(0, index),
  {
    // here update data value
    ...array[index],
    [label]: newValue,
  },
  ...array.slice(index + 1),
];

console.log(updatedArray);

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44524121

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档