簡體   English   中英

向數組對象添加屬性

[英]Adding property to array Object

目前,我有一個數組對象[{}]代碼,該代碼是

const updatedDat = response.data
const updatedData = []
for (let i=0; i<5; i++) {
    updatedData.push(updatedDat[i])
}
console.log(updatedData)

上面的console.log日志

Array(5)
0:{userId: 1, id: 1, title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body: "quia et suscipit↵suscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto"}

1:{userId: 1, id: 2, title: "qui est esse", body: "est rerum tempore vitae↵sequi sint nihil reprehend…aperiam non debitis possimus qui neque nisi nulla"}

2:{userId: 1, id: 3, title: "ea molestias quasi exercitationem repellat qui ipsa sit aut", body: "et iusto sed quo iure↵voluptatem occaecati omnis e…↵molestiae porro eius odio et labore et velit aut"}

3:{userId: 1, id: 4, title: "eum et est occaecati", body: "ullam et saepe reiciendis voluptatem adipisci↵sit … ipsam iure↵quis sunt voluptatem rerum illo velit"}

4:{userId: 1, id: 5, title: "nesciunt quas odio", body: "repudiandae veniam quaerat sunt sed↵alias aut fugi…sse voluptatibus quis↵est aut tenetur dolor neque"}
length:5

現在,我想在這個名為author的對象內添加另一個字段,因此應如下所示

1:{Author:"Max" userId: 1, id: 2, title: "qui est esse", body: "est rerum tempore vitae↵sequi sint nihil reprehend…aperiam non debitis possimus qui neque nisi nulla"}

我該如何實現?

您可以通過一個簡單的forEach循環來實現它:

updatedData.forEach((obj)=>{
  obj.Author = "max";
});

假設要將該鍵添加到數組中的特定對象:

let arr = [
  {name: 'will', id: 1},
  {name: 'bill', id: 2}
];

const foundItem = arr.find(item => item.id === 1);
foundItem.author = 'foo';

console.log(arr);

在for循環中,在插入屬性之前將其添加。

for (let i=0; i<5; i++) {
    updatedDat[i].Author = "Max";
    updatedData.push(updatedDat[i])
}

如果我們必須在數組元素中添加屬性,則必須在0索引中添加以下代碼,這對您有幫助

 const updatedDat = [{id:"1"}]; updatedDat[0].auther = "some name" const updatedData = [] for (let i=0; i<updatedDat.length; i++) { updatedData.push(updatedDat[i]) } console.log(updatedData) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM