作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
我是一名优秀的程序员,十分优秀!