2 回答
TA贡献1839条经验 获得超15个赞
我会选择一种递归/以编程方式构建所需数据结构的方法,而不是通过删除不需要的属性来改变现有的输入数据......
// {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个赞
假设您获得的对象数组的Children属性是对象数组或空 arr 指示它是叶子,您可以使用以下函数的组合删除叶子节点
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
添加回答
举报