【问题标题】:java script deep searching through a tree with lodashjavascript 用 lodash 深度搜索一棵树
【发布时间】:2021-03-23 12:46:16
【问题描述】:

我有一个包含如下对象的数组:

 tree = [
        {
          id: 1,
          name: "parent1",
          children: [
            {
              id: 2,
              name: "child1",
              children: [
                { id: 4, name: "subChild1",dateType:"hijri" },
                { id: 5, name: "subChild2",dateType:"hijri" }
              ]
            },
            { id: 3, name: "child2" }
          ]
        }
      ];

还有另一个数组,例如:

  result=  [{id:4,dateType:"Geo"},{id:5,dateType:"another"}]

我想遍历第二个数组,并且对于第一个数组中的每个节点都满足条件 id=id ,我需要更改它的 dateType 值,如下所示:

 this.result.forEach(res => {
        this.flattenItems(this.tree).find(
          item => item.id == res.id
        ).itemType =res.dateType;
      });

注意这棵树来自 3 层,并且只在最后一层进行操作

有没有办法使用lodash实现循环?

【问题讨论】:

    标签: javascript collections treeview lodash


    【解决方案1】:

    我们可以递归地做到这一点:

    • 首先检查对象是否具有children 属性。如果是,则通过 children 数组查看对象是否具有 dateType 属性。
    • 如果子数组对象没有dateType 属性,而是他们有进一步的children,则为该children 数组再次递归调用该方法:

    const tree = [{ id: 1, name: "parent1", children: [{ id: 2, name: "child1", children: [{ id: 4, name: "subChild1",dateType:"hijri" }, { id: 5, name: "subChild2",dateType:"hijri" }]}, { id: 3, name: "child2" } ]}];
    const result = [{id:4,dateType:"Geo"},{id:5,dateType:"another"}];
    
    const changeDateType = (arr) => {
      if(arr && arr.hasOwnProperty("children")){
          arr.children.forEach(o => {
            if(o.hasOwnProperty("dateType")){
              const child = result.find(d => d.id == o.id);
              o.dateType = child ? child.dateType : o.dateType;
            }
            else{
              changeDateType(o);
            }
          });
      }
      return arr;
    }
    console.log(tree.map(t => changeDateType(t)));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-11
      • 1970-01-01
      • 2020-07-19
      • 2013-07-03
      • 1970-01-01
      • 2011-11-28
      • 1970-01-01
      相关资源
      最近更新 更多