【问题标题】:How do I deep filter array and keep array tree structure如何深度过滤数组并保持数组树结构
【发布时间】:2022-01-12 05:52:11
【问题描述】:

我需要从嵌套数组中删除项目。我成功地做到了这一点,但是我需要保持树的完整结构。当前代码输出things 对象并删除了name 等于'child thing 1' 的元素,但是我的结果遗漏了原始树中的许多其他数据。

我正在使用lodashdeepdash,因为我将使用带有许多孩子的对象。

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' &amp;&amp; value !== 'child thing 1') ...不需要if 子句或parent 参数。

标签: javascript arrays data-structures filter lodash


【解决方案1】:

正如@grodzi 在 cmets 中指出的那样,您的问题不清楚您的预期结果是什么。但是,您似乎只是在寻找一种方法来快速删除对象中的子结构,同时保持其整体完整性。 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
));

我认为这样的事情可以完成工作。不过,请务必自行检查,如果可能部署,最好进行测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多