gpt4 book ai didi

javascript - 设置对象格式

转载 作者:行者123 更新时间:2023-12-02 23:55:01 25 4
gpt4 key购买 nike

我正在尝试重构嵌套对象:

输入

{
"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]);
});

最佳答案

您可以使用这个(箭头)函数,它使用 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));

关于javascript - 设置对象格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55438236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com