如何深度过滤数组并保持数组树结构



我需要从嵌套数组中删除项。我已经成功地做到了这一点,但我需要保持树的完整结构。当前代码输出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>

正如@grodzi在评论中指出的那样,从你的问题中还不清楚你期望的结果是什么。然而,您似乎只是在寻找一种方法来快速删除对象中的子结构,同时保持其整体完整性。Lodash提供了一些漂亮的功能,可以简化这样的任务。

有助于手头任务的两个是getomit


const pathsToRemove = ['things.1.children.0']; // use object dot notation (.) even for array elements 
const restructure = (object, pathsToRemove) => pathsToRemove.reduce((acc, path) => {
const parentPath = path.split('.').slice(0,-1).join('.');
const [targetPath] = path.split('.').slice(-1);
let parent = _.get(acc, parentPath);
if (parent.constructor === Array) {
// this block is to prevent empty array items
parent.splice(+targetPath, 1);
return acc;
}
return _.omit(acc, path);
}, object);
console.log(JSON.stringify(
restructure(things, pathsToRemove),
null,
4
));

我认为这样的事情可以完成这项工作。不过,一定要自己检查一下,如果有可能部署的话,最好进行测试。

最新更新