【发布时间】:2020-05-05 18:19:07
【问题描述】:
我正在研究 reduce 在 javascript 中的使用,并且我正在尝试以通用方式重组对象数组 - 需要是动态的。
flowchart - 我完全迷路了
我从这个开始。每个 ID 都成为一个 Key。 每个 PARENT 都标识它属于哪个 Key。
我有这个:
const in = [
{
"id": "Ball",
"parent": "Futebol"
},
{
"id": "Nike",
"parent": "Ball"
},
{
"id": "Volley",
"parent": null
}
]
我想要这个
out = {
"Futebol": {
"Ball": {
"Nike": {}
}
},
"Volley": {}
}
我试了一下 - 我惨败了。
const tree = require('./mock10.json')
// Every ID becomes a Key.
// Every PARENT identifies which Key it belongs to.
const parsedTree = {}
tree.reduce((acc, item) => {
if (parsedTree.hasOwnProperty(item.parent)){
if (parsedTree[`${item.parent}`].length > 0) {
parsedTree[`${item.parent}`][`${item.id}`] = {}
} else {
parsedTree[`${item.parent}`] = { [`${item.id}`]: {} }
}
} else {
// i get lost in logic
}
}, parsedTree)
console.log(parsedTree)
【问题讨论】:
-
元素嵌套的数量限制是多少?
-
我不想考虑限制。为了研究这个,我创建了 3 个模拟:10 个对象中的一个,50 个和 1000 个中的另一个。
-
如果有无限的关卡,事情就会变得更加复杂......
标签: javascript json data-structures