使用现有属性值添加新的JSON属性

时间:2019-10-17 04:05:28

标签: javascript arrays json

我有一个JSON序列化数据文件,如下所示:

{
    "name":"Store",
    "children":[
        {
            "name":"Store 1",
            "children":[
                {
                    "name":"collection 1",
                    "description":"collection 1",
                    "children":[
                        {
                            "name":"Products",
                            "description":"Products",
                            "children":[
                                {
                                    "name":"Product 1",
                                    "description":"Product 1"
                                }
                            ]
                        }
                    ]
                }
            ],
            "description":"category 1"
        },
        {
            "name":"Store 2"
        }
    ]
}

对于具有name属性的对象,我想添加一个title,其值与name属性的值相同。以下是我尝试将JSON转换为的内容:

{
    "name":"Store",
    "title":"Store",
    "children":[
        {
            "name":"Store 1",
            "title":"Store 1",
            "children":[
                {
                    "name":"collection 1",
                    "title":"collection 1",
                    "description":"collection 1",
                    "children":[
                        {
                            "name":"Products",
                            "title":"Products",
                            "description":"Products",
                            "children":[
                                {
                                    "name":"Product 1",
                                    "title":"Product 1",
                                    "description":"Product 1"
                                }
                            ]
                        }
                    ]
                }
            ],
            "description":"category 1"
        },
        {
            "name":"Store 2",
            "title":"Store 2"
        }
    ]
}

2 个答案:

答案 0 :(得分:2)

我们可以使用JSON解析Json.Parse并使用递归为所有子代添加标题如下

INSERT INTO kpi (key_competency, user)
SELECT 'a', 'Jon Skeet'
WHERE NOT EXISTS (SELECT 1 FROM kpi WHERE user = 'Jon Skeet' AND key_competency = 'a');

答案 1 :(得分:0)

const addTitleRec = (j) => {
  j.title = j.name, j.children && j.children.forEach(addTitleRec);
}

const json = {
  "name": "Store",
  "children": [{
      "name": "Store 1",
      "children": [{
        "name": "collection 1",
        "description": "collection 1",
        "children": [{
          "name": "Products",
          "description": "Products",
          "children": [{
            "name": "Product 1",
            "description": "Product 1"
          }]
        }]
      }],
      "description": "category 1"
    },
    {
      "name": "Store 2"
    }
  ]
};

addTitleRec(json);

console.log(json);