gpt4 book ai didi

javascript - 将json转换为其他json结构

转载 作者:行者123 更新时间:2023-11-29 20:53:26 25 4
gpt4 key购买 nike

我有一个具有这种结构的对象数组:

const treeData = [
{ 0: ["0-0", "0-1"] },
{ 1: ["1-0", "1-1"] }
]

它可能更深,但数组数据总是 json 或字符串

const treeData = [
{ 0: ["0-0", "0-1"] },
{ 1: ["1-0", "1-1"] },
2,
3
]

我想得到这样的东西:

const treeDataResult = [
{
label: "0",
value: "0",
children: [
{
label: "0-0",
value: "0-0"
},
{
label: "0-1",
value: "0-1",
}
]
},
{
label: "1",
value: "1",
children: [
{
label: "1-0",
value: "1-0",
},
{
label: "1-1",
value: "1-1",
}
]
},
{
label: "2",
value: "2"
},
{
label: "3",
value: "3"
}
]

我现在的代码是这样的:

const treeData = [
{ "0": ["0-0", "0-1"] },
{ "1" : ["1-0", "1-1"] }
];

const convertNode = (parentNode) =>
parentNode.map(
childnode => {
if (typeof(childNode) === 'string')
return {
label: childNode,
value: childNode
}
else
return
childNode.map((key, val) =>
({
label: key,
value: key,
children: convertNode(val)
})
)
}
)

var treeDataResult = convertNode(treeData);
console.log(treeDataResult);

最佳答案

如果使用JSON.parse来获取数据,你可以这样尝试:

var j = '[ { "0": ["0-0", "0-1"] }, { "1": ["1-0", "1-1"] }, 2, 3 ]'

var o = JSON.parse(j, (k, v) => (k = v.constructor) === Array ? v :
k !== Object ? ({ label: v, value: v }) :
({ label: k = Object.keys(v)[0], value: k, children: v[k] }) )

console.log( o )

关于javascript - 将json转换为其他json结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50573749/

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