【发布时间】:2022-01-12 05:52:11
【问题描述】:
我需要从嵌套数组中删除项目。我成功地做到了这一点,但是我需要保持树的完整结构。当前代码输出things 对象并删除了name 等于'child thing 1' 的元素,但是我的结果遗漏了原始树中的许多其他数据。
我正在使用lodash 和deepdash,因为我将使用带有许多孩子的对象。
deepdash(_);
let things = {
type: 'app',
info: [],
things: [{
name: 'something',
good: false,
}, {
name: 'another thing',
good: true,
children: [{
name: 'child thing 1',
good: false,
}, {
name: 'child thing 2',
good: true,
}, {
name: 'child thing 3',
good: false,
}],
}, {
name: 'something else',
good: true,
subItem: {
name: 'sub-item',
good: false,
},
subItem2: {
name: 'sub-item-2',
good: true,
},
}],
};
let filtrate = _.filterDeep(things, (value, key, parent) => {
if (key == 'name' && parent.name !== 'child thing 1') return true;
});
console.log({ filtrate });
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script src="https://cdn.jsdelivr.net/npm/lodash/lodash.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/deepdash/browser/deepdash.min.js"></script>
【问题讨论】:
-
请输入预期输出
-
according to the documentation OP 可能需要传递并更改一些额外的
options。 ...顺便说一句,return 语句可能会被重写为更直接的内容...return (key === 'name' && value !== 'child thing 1')...不需要if子句或parent参数。
标签: javascript arrays data-structures filter lodash