[英]add key and value to the last duplicated object in array
I have an array of object and I want to add a key and value to the objects that are duplicated.我有一个 object 数组,我想为重复的对象添加一个键和值。
[
{type: "text", content: ""},
{type: "option", content: ""},
{type: "text", content: ""},
{type: "link", url: ""},
{type: "text", content: ""},
{type: "text", content: ""},
{type: "text", content: ""},
]
how should I add my key and value to the last text type, its dynamic and will change.我应该如何将我的键和值添加到最后一个文本类型,它是动态的并且会改变。
result:结果:
[
{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.