首页 > 解决方案 > Lodash 过滤和删除类似 java 流

问题描述

我在使用 lodash 的 nodejs 应用程序中有一个树数据结构:

var l = require("lodash");

obj_string = 
`
[
    {
      "father_id": 1,
      "name": "father 1",
      "child_array": [
        {
          "id": 11,
          "name": "father 1 child 1"
        },
        {
          "id": 12,
          "name": "father 1 child 2"
        }
      ]
    },
    {
      "father_id": 2,
      "name": "father 2",
      "child_array": [
        {
          "child_id": 21,
          "name": "father 2 child 1"
        },
        {
          "child_id": 22,
          "name": "father 2 child 2 - TO DELETE"
        }
      ]
    }  
  ]
`;
tree = JSON.parse(obj_string);

我想通过 id 删除一个孩子,但我不知道他的父亲是什么:

l.chain(tree).flatMap(f=>f.child_array).remove(c=>c.child_id==22);

它不起作用,为什么!我使用了 java 流,但我不明白 lodash 是如何工作的。例如,如果我想搜索一个孩子并且我想引用已创建的孩子,例如为了编辑它的成员(没有 _.map),我该​​怎么办?

有了这个:

ret = l.chain(tree).flatMap(f=>f.child_array).find(c=>c.child_id==22).value();

我在 ret 中有一个新对象,所以我无法访问/编辑原始对象。换句话说,第二个问题是:如何从 lodash 包装器中检索对象引用?

标签: javascriptarraysnode.jsstreamlodash

解决方案


Here is an answer using object-scan. We use object-scan for a lot of our data processing.

Note that this solution will modify the original object.

// const objectScan = require('object-scan');

const prune = (id, input) => objectScan(['**'], {
  abort: true, // abort after first match
  rtn: 'bool',
  filterFn: ({ value, parent, property }) => {
    if (value.child_id === id) {
      parent.splice(property, 1);
      return true;
    }
    return false;
  }
})(input);

const obj = [ { father_id: 1, name: 'father 1', child_array: [ { id: 11, name: 'father 1 child 1' }, { id: 12, name: 'father 1 child 2' } ] }, { father_id: 2, name: 'father 2', child_array: [ { child_id: 21, name: 'father 2 child 1' }, { child_id: 22, name: 'father 2 child 2 - TO DELETE' } ] } ];

console.log(prune(22, obj)); // returns true iff replacement made
// => true
console.log(obj);
// => [ { father_id: 1, name: 'father 1', child_array: [ { id: 11, name: 'father 1 child 1' }, { id: 12, name: 'father 1 child 2' } ] }, { father_id: 2, name: 'father 2', child_array: [ { child_id: 21, name: 'father 2 child 1' } ] } ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>

Disclaimer: I'm the author of object-scan


推荐阅读