[英]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.