微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将“键”:“值”对添加到“值”在不同数组上迭代的嵌套对象数组中?

如何解决如何将“键”:“值”对添加到“值”在不同数组上迭代的嵌套对象数组中?

我有一个像这样的对象数组,其中可以有更多或更少的项目:

arrOfItems = [
    {
        "type": "apple","earth: "blue"
    }
    {
        "type": "orange","attrs": {
            "id": 21,"data": "RET","data2": null,"order": null,"order2": null,"type": "property","char": "@"
        }
    },{
        "type": "apple","earth: "green"
    },"earth: "yellow"
    },{
        "type": "orange","attrs": {
            "id": 28,"data": "EMC",]

数组中的每一项都有一个结构。因此,如果“type”=“apple”,则将添加一个键“earth”。如果 "type" = "orange",则会添加一个键 "attrs",其结构如下:

"attrs": {
    "id":,"data": "","type": "","char": ""
}

对于类型为“orange”的每个项目,我如何向 attrs 对象添加一个键“类”,其中该键被分配给以下数组中的一个项目:

arrOfProps = ["prop_1","prop_2","prop_3","prop_4" "prop_5","prop_6"]

例如,基于上面的 arrOfItems,我如何获得以下内容

arrOfItems = [
    {
        "type": "apple","attrs": {
            "class": "prop_1","id": 21,"attrs": {
            "class": "prop_2","id": 28,......... For the next item with "type": "orange",we have "class": "prop_3",etc.
]

到目前为止,我已经:

arrOfItems.forEach( element =>
    if(element.type === "orange") {
        obj.attrs["class"] = arrOfProps[??];
    }
)

但是我不确定如何更进一步。有人会知道吗?

解决方法

你可以简单地迭代这个,同时跟踪分配的道具:

const arrOfItems = [
    { type: 'apple',earth: 'blue' },{
        "type": "orange","attrs": {
            "id": 21,"data": "RET","data2": null,"order": null,"order2": null,"type": "property","char": "@"
        }
    },{ type: 'apple',earth: 'green' },earth: 'yellow' },"attrs": {
            "id": 28,"data": "EMC",]

const arrOfProps = ["prop_1","prop_2","prop_3","prop_4","prop_5","prop_6"];

let nextProp = 0;
for (const element of arrOfItems) {
    if (element.type !== 'orange') continue;
    element.attrs.class = arrOfProps[nextProp++];
}

console.log(arrOfItems);

当然,如果你的橙子比 arrOfProps 中的元素多,那么 class 将被分配给 undefined

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。