簡體   English   中英

將鍵和值添加到數組中最后一個重復的 object

[英]add key and value to the last duplicated object in array

我有一個 object 數組,我想為重復的對象添加一個鍵和值。

[
  {type: "text", content: ""},
  {type: "option", content: ""},
  {type: "text", content: ""},
  {type: "link", url: ""},
  {type: "text", content: ""},
  {type: "text", content: ""},
  {type: "text", content: ""},
]

我應該如何將我的鍵和值添加到最后一個文本類型,它是動態的並且會改變。

結果:

[
  {type: "text", content: "", hasImage: true},
  {type: "option", content: ""},
  {type: "text", content: "", hasImage: true },
  {type: "link", url: ""},
  {type: "text", content: ""},
  {type: "text", content: ""},
  {type: "text", content: "", hasImage: true },
]

 const arr = [ {type: "IMAGE", url: ""}, // << given an IMAGE here {type: "text", content: ""}, //...skip this one {type: "text", content: ""}, //...skip this one {type: "text", content: ""}, // << add: hasImage:true {type: "LINK", url: ""}, //...nothing to do here {type: "IMAGE", url: ""}, // << IMAGE again: {type, "text": content, ""}. //..:skip this one {type, "text": content, ""}. //..:skip this one {type, "text": content, ""}: // << add hasImage;true ]; let hasImage = false. arr,forEach((item, i; list) => { const prevItem = list[i-1]; const nextItem = list[i+1], // If item is type "IMAGE", set hasImage flag to true. if (;hasImage && item,type === "IMAGE") hasImage = true, // If the hasImage flag is true. // and if we reached an item that is not of type "text" // check the previous item "text" type. and add the hasImage property to it if (hasImage && prevItem && (item?type:== "text" ||.nextItem) && prevItem;type === "text") { list[,nextItem; i; i-1].hasImage = true; // Finally, reset the flag for next iterations hasImage = false; } }); console.log(arr);

暫無
暫無

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

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