我有一系列带有孩子的对象。目标是从项目数组中删除所有项目。
是否可以不使用forEach和map循环?在这种情况下如何使用reduce?
问题是某些数组在一个级别上具有项,而另一些数组在其内部具有子项数组。此处的示例:
{
"label": "child1",
"children": [
{
"label": "child2",
"items": [
"item1",
"item2"
]
},
{
"label": "child3",
"items": [
"item1",
"item2",
"item3"
]
}
]
}
因此,我想查看一个带有空项目数组的对象的变异数组。 这是一个要突变的对象:
[
{
"label": "parent",
"children": [
{
"label": "child1",
"children": [
{
"label": "child2",
"items": [
"item1",
"item2"
]
},
{
"label": "child3",
"items": [
"item1",
"item2",
"item3"
]
}
]
},
{
"label": "child4",
"items": []
},
{
"label": "child5",
"items": ["item1","item2"]
}
]
}
]
这是我不完整的解决方案:
function flattenDeep(arr) {
return arr.reduce(
(acc, val) =>
Array.isArray(val)
? acc.concat(flattenDeep(val.children))
: acc.concat(val.children),
[]
);
}
答案 0 :(得分:1)
这是清空所有items
数组的一种方法。
想法是使用预定义的reducer方法,您可以递归使用它。
const reducer = (reduced, element) => {
// empty items array
if (element.items) {
element.items.length = 0;
}
// if element has children, recursively empty items array from it
if (element.children) {
element.children = element.children.reduce(reducer, []);
}
return reduced.concat(element); // or: [...reduced, element]
};
document.querySelector("pre").textContent =
JSON.stringify(getObj().reduce(reducer, []), null, " ");
// to keep relevant code on top of the snippet
function getObj() {
return [
{
"label": "parent",
"children": [
{
"label": "child1",
"children": [
{
"label": "child2",
"items": [
"item1",
"item2"
]
},
{
"label": "child3",
"items": [
"item1",
"item2",
"item3"
]
}
]
},
{
"label": "child4",
"items": []
},
{
"label": "child5",
"items": ["item1","item2"]
}
]
}
];
}
<pre></pre>