我有一个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"
}
]
}
我们可以使用JSON.Parse解析Json并使用递归为所有子代添加标题,如下所示:>
function Recursion(items) {
items["title"] = items["name"]
if (items["children"] != undefined) {
items["children"].forEach(element => {
element = Recursion(element)
});
}
return items
}
var text = '{"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"}]}';
var item = JSON.parse(text);
item = Recursion(item);