我正在尝试重组嵌套对象:
输入
{
"elements":[
{
"name":"catalog",
"elements":[
{
"name":"book",
"elements":[
{
"name":"author",
"elements":[
{
"type":"text",
"text":"Gambardella, Matthew"
}
]
},
{
"name":"title",
"elements":[
{
"text":"XML Developers Guide"
}
]
}
]
}
]
}
]
}
所需的输出
{
"children":[
{
"text": {"name":"catalog"},
"children":[
{
"text": {"name":"book"},
"children":[
{
"text": {"name":"author"},
"children":[
{
"type":"text",
"text":"Gambardella, Matthew"
}
]
},
{
"text": {"name":"title"},
"children":[
{
"text": {"name": "XML Developers Guide"}
}
]
}
]
}
]
}
]
}
到目前为止,我已经尝试过
function createJsonStructure(obj) {
for (var i = 0; i < obj.elements.length; ++i) {
console.log(obj.name);
if(obj.elements[i].elements) {
for (var ii = 0; ii < obj.elements[i].elements.length; ++ii) {
createJsonStructure(obj.elements[i].elements[ii]);
}
} else {
console.log(obj.elements[i].text);
}
}
};
$(function(){
createJsonStructure(xmlToJson.elements[0]);
});
答案 0 :(得分:1)
您可以使用使用spread syntax in object literals(ES2018)的此(箭头)函数:
const arrange = obj => obj.elements ? {
..."name" in obj && { text: { name: obj.name } },
children: obj.elements.map(arrange)
} : {...obj};
// Sample:
const data = {"elements":[{"name":"catalog","elements":[{"name":"book","elements":[{"name":"author","elements":[{"type":"text","text":"Gambardella, Matthew"}]},{"name":"title","elements":[{"text":"XML Developers Guide"}]}]}]}]};
console.log(arrange(data));
如果还需要转换叶节点中的现有“文本”属性(在输出中不明确):
const arrange = obj => ({
..."type" in obj && { type: obj.type },
..."name" in obj && { text: { name: obj.name } },
..."text" in obj && { text: { name: obj.text } },
..."elements" in obj && { children: obj.elements.map(arrange) }
});
// Sample:
const data = {"elements":[{"name":"catalog","elements":[{"name":"book","elements":[{"name":"author","elements":[{"type":"text","text":"Gambardella, Matthew"}]},{"name":"title","elements":[{"text":"XML Developers Guide"}]}]}]}]};
console.log(arrange(data));