【发布时间】:2022-01-20 08:24:21
【问题描述】:
我有一组嵌套对象。我想编辑它们中的每一个并添加属性 "status" 并且该属性的值可以是 "selected"、"unselected" 或 “缩进”。
1.状态:'选中'
- 他的 lvlScope 数组不为空
- lvlScope 他所有孩子的数组不为空
2.状态:'未选中'
- 他的 lvlScope 数组为空
- lvlScope 他所有孩子的数组都是空的
3.状态:'缩进'
- 他的 lvlScope 数组为空,并且他的至少一个孩子的 lvlScope 数组不为空
- 他的 lvlScope 数组不为空,并且他的至少一个孩子的 lvlScope 数组为空
- 他的 lvlScope 数组不为空,他所有的孩子都有 lvlScope 数组为空
所有子级表示所有嵌套的子级
有人知道怎么做吗?
let data = [{
id: 1,
name: 'level1',
lvlScope: [1, 2, 3],
lvl1Subs: []
},
{
id: 2,
name: 'level1',
lvlScope: [],
lvl1Subs: [{
id: 1,
name: 'level2',
lvlScope: [],
lvl2Subs: [{
id: 1,
name: 'level3',
lvlScope: [],
lvl3Subs: []
},
{
id: 2,
name: 'level3',
lvlScope: [1, 2],
lvl3Subs: []
},
{
id: 3,
name: 'level3',
lvlScope: [1],
lvl3Subs: [{
id: 1,
name: 'level4',
lvlScope: [],
lvl4Subs: [{
id: 1,
name: 'level5',
lvlScope: []
},
{
id: 2,
name: 'level5',
lvlScope: [1]
}
]
},
{
id: 2,
name: 'level4',
lvlScope: [],
lvl4Subs: []
}
]
}
]
},
{
id: 2,
name: 'level2',
lvlScope: [1],
lvl2Subs: []
}
]
},
{
id: 3,
name: 'level1',
lvlScope: [],
lvl1Subs: [{
id: 1,
name: 'level2',
lvlScope: [1, 2],
lvl2Subs: []
},
{
id: 2,
name: 'level2',
lvlScope: [],
lvl2Subs: []
},
{
id: 3,
name: 'level2',
lvlScope: [1, 2, 3],
lvl2Subs: [{
id: 1,
name: 'level3',
lvlScope: [],
lvl3Subs: []
}]
},
{
id: 4,
name: 'level2',
lvlScope: [],
lvl2Subs: []
},
{
id: 5,
name: 'level2',
lvlScope: [1, 2],
lvl2Subs: []
}
]
}
]
const levels = (data) => {
data.map((lvl1) => {
console.log('-lvl1', lvl1)
lvl1.lvl1Subs.map((lvl2) => {
console.log('--lvl2', lvl2)
lvl2.lvl2Subs.map((lvl3) => {
console.log('---lvl3', lvl3)
lvl3.lvl3Subs.map((lvl4) => {
console.log('----lvl4', lvl4)
lvl4.lvl4Subs.map((lvl5) => {
console.log('-----lvl5', lvl5)
})
})
})
})
})
}
console.log(levels(data))
【问题讨论】:
-
您能否详细说明您为实现预期结果所做的工作?您已经有了一些代码,用于显示/打印您可以开始的不同级别。此外,您可能希望研究递归来解决其中的一些问题。