我有一組嵌套物件。我想編輯它們中的每一個并添加屬性"status"并且該屬性的值可以是"selected"、"unselected"或"indent"。
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))
uj5u.com熱心網友回復:
你可以用遞回函式的方式輕松解決這個問題。
uj5u.com熱心網友回復:
當關卡沒有孩子時,你沒有說要分配什么。此外還不清楚是否應該只對直接子節點或嵌套子節點進行檢查。這是一個解決方案,考慮到沒有孩子意味著selected或unselected只考慮檢查直接孩子。
const addStatus = (data, level = 1) => {
const scope = emptyScope(data);
let childrenScopes = [];
for (let child of data["lvl" level "Subs"]
? data["lvl" level "Subs"]
: []) {
childrenScopes.push(emptyScope(child));
addStatus(child, level 1);
}
let status = "indent";
let found = childrenScopes.find((c) => c === !scope);
if (found === true || found === false) {
found = true;
} else {
found = false;
}
if ((!found || !childrenScopes.length) && !scope) {
status = "selected";
}
if ((!found || !childrenScopes.length) && scope) {
status = "unselected";
}
data["status"] = status;
};
const emptyScope = (data) => {
if (data.lvlScope.length > 0) {
return false;
}
return true;
};
data.map((d) => addStatus(d, 1));
console.log(data);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/383626.html
標籤:javascript 嵌套对象
上一篇:400或500級別的Http回應
