gpt4 book ai didi

javascript - 将两个列表转换为 json

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

我正在尝试将两个列表转换为 json。

例如:

l1 = ['a','b','a']
l2 = ['q','r','s']

应转换为:

[{
"name": "g",
"children": [{
"name": "a",
"children": [{
"name": "q"
}, {
"name": "s"
}]
},
{
"name": "b",
"children": [{
"name": "r"
}]
}
]
}]

我最接近的是:

l1 = ['a','b','a']
l2 = ['q','r','s']

nameDict = {}
childrenDict = {}

l1 = l1.map(x => {
return({name: x});
});
console.log(l1);

l2 = l2.map(x => {
return({children: x});
});
console.log(l2);

var c = l1.map(function(e, i) {
return [e, l2[i]];
});

console.log(JSON.stringify(c))

产生:

[[{"name":"a"},{"children":"q"}],
[{"name":"b"},{"children":"r"}],
[{"name":"a"},{"children":"s"}]]

如何组合产生的元素? :

[{
"name": "g",
"children": [{
"name": "a",
"children": [{
"name": "q"
}, {
"name": "s"
}]
},
{
"name": "b",
"children": [{
"name": "r"
}]
}
]
}]

最佳答案

免责声明:由于我们不知道 g 来自哪里,因此我只会构建根 children 数组。

由于您的数组具有相同的长度,因此您可以使用普通的 for 并与索引一起使用来处理两个数组。只需构建一个数组并检查每次迭代是否“子”已经存在。如果没有,请创建它。

l1 = ['a','b','a']
l2 = ['q','r','s']

let gChildren = []
for(let i = 0; i < l1.length; i++){
let group = gChildren.find(c => c.name === l1[i])
if(!group){
group = { name: l1[i], children: [] }
gChildren.push(group)
}

group.children.push({ name: l2[i] })
}

console.log(gChildren)

关于javascript - 将两个列表转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56972787/

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