gpt4 book ai didi

javascript - 如何从两个字符串数组制作 JSON - 第一个数组具有值,第二个数组具有相同序列的 ID

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

Array 1 = Accessories:Bracket,Accessories:Clamp,Actuator:Accessories,Actuator:Accessories:Bracket,Actuator:Accessories:Clamp,Actuator:Clevis

Array 2 = 24092859,24092784,24094450,24094451,24110219,24092811

所需输出 =

[
{
"text": "Accessories",
"children": [
{
"text": "Bracket",
"children": [],
"mtdtId": "24092859"
},
{
"text": "Clamp",
"children": [],
"mtdtId": "24092784"
}
],
"mtdtId": "24092859,24092784"
},
{
"text": "Actuator",
"children": [
{
"text": "Accessories",
"children": [
{
"text": "Bracket",
"children": [],
"mtdtId": "24094451"
},
{
"text": "Clamp",
"children": [],
"mtdtId": "24110219"
}
],
"mtdtId": "24110219,24094451"
},
{
"text": "Clevis",
"children": [],
"mtdtId": ""
}
],
"mtdtId": "24110219,24094451"
}
]

父节点应包含子节点的 ID。

最佳答案

const array1 = "Accessories:Bracket,Accessories:Clamp,Actuator:Accessories,Actuator:Accessories:Bracket,Actuator:Accessories:Clamp,Actuator:Clevis".split(
","
);
const array2 = "24092859,24092784,24094450,24094451,24110219,24092811".split(
","
);

const output = array1.reduce(
(topLevelNodes, path, i) => {
let nodes = topLevelNodes;
let mtdId = array2[i];
path.split(":").forEach(text => {
let node = nodes.filter(child => child.text === text)[0];
if (node) {
node.mtdId += "," + mtdId;
} else {
nodes.push((node = { text, children: [], mtdId }));
}
nodes = node.children;
});
return topLevelNodes;
},
[]
);

console.log(output);

关于javascript - 如何从两个字符串数组制作 JSON - 第一个数组具有值,第二个数组具有相同序列的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42946636/

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