繁体   English   中英

如何在 Nodejs 的数组中更新 object?

[英]How can I update object in an array in Nodejs?

这是我的数组

const arr = [
{ id: "1", hello: "hello1" },
{ id: "2", hello: "hello2" },

];

我想要这个代码

const finalarr = [
{ id: "1", hello: "hello1", bye: 'bye1' },
{ id: "2", hello: "hello2", bye: 'bye2' },

];

尝试使用map

 var arr = [{ id: "1", hello: "hello1" },{ id: "2", hello: "hello2" }]; result = arr.map(elem=>({...elem, 'bye':`bye${elem.id}`})); // with attaching the id result2 = arr.map((elem,i)=>({...elem, 'bye':`bye${i+1}`})); // by generating id; console.log(result); console.log(result2);

通过在代码中使用以下循环,您可以获得所需的 output。

  for (var i =0;i<arr.length;i++){
    arr[i]["bye"] = "bye"+(i+1); 
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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