2 回答

TA貢獻1839條經驗 獲得超15個贊
我會選擇一種遞歸/以編程方式構建所需數(shù)據(jù)結構的方法,而不是通過刪除不需要的屬性來改變現(xiàn)有的輸入數(shù)據(jù)......
// {Children: [], Label: "some str", Value: some int, Properties:[] }
const data = {
Label: "root_with_children",
Value: 1,
Properties: ["foo", "bar"],
Children: [{
Label: "level_1_without_children",
Value: 2,
Properties: ["foo", "bar"],
Children: []
}, {
Label: "level_1_with_children",
Value: 3,
Properties: ["foo", "bar"],
Children: [{
Label: "level_2_without_children",
Value: 4,
Properties: ["foo", "bar"],
Children: []
}, {
Label: "level_2_with_children",
Value: 5,
Properties: ["foo", "bar"],
Children: [{
Label: "level_3_without_children",
Value: 6,
Properties: ["foo", "bar"],
Children: []
}]
}]
}]
};
function isNonEmtyArray(type) {
return (Array.isArray(type) && (type.length >= 1));
}
function collectItemsWithChildrenOnly(list, item) {
const { Children } = item;
if (isNonEmtyArray(Children)) {
const copy = Object.assign({}, item, { Children: [] });
list.push(copy);
Children.reduce(collectItemsWithChildrenOnly, copy.Children);
}
return list;
}
let test;
test = [data].reduce(collectItemsWithChildrenOnly, []);
console.log('1st run :: test : ', test);
test = test.reduce(collectItemsWithChildrenOnly, []);
console.log('2nd run :: test : ', test);
test = test.reduce(collectItemsWithChildrenOnly, []);
console.log('3rd run :: test : ', test);
test = test.reduce(collectItemsWithChildrenOnly, []);
console.log('4th run :: test : ', test);
test = test.reduce(collectItemsWithChildrenOnly, []);
console.log('countercheck :: test : ', test);
.as-console-wrapper { min-height: 100%!important; top: 0; }

TA貢獻1820條經驗 獲得超10個贊
假設您獲得的對象數(shù)組的Children屬性是對象數(shù)組或空 arr 指示它是葉子,您可以使用以下函數(shù)的組合刪除葉子節(jié)點
const removeEmptyChildren = obj => obj.Children.length
?
{...obj,Children:leafRemover(obj.Children)}
:
undefined
const leafRemover = arr => arr.filter( e => removeEmptyChildren(e) !== undefined)
console.log(leafRemover(data)) // where data is array of objects from the server
添加回答
舉報