通过父ID递归搜索后代

时间:2019-04-24 21:49:50

标签: javascript arrays lodash

我有平面数组(平面树)。如何使用Lodash库通过parentIds对子项进行递归搜索?

例如,通过id = 1,我需要获取“ JavaScript”,“ React”和“ Vue”。

array: 
  [{
    id: 1,
    name: 'Development',
    parentIds: [],
  },
  { 
    id: 2,
    name: 'JavaScript',
    parentIds: [1] 
  },
  { 
    id: 3,
    name: 'React',
    parentIds: [2]
   },
   {
     id: 4,
     name: "Vue",
     parentIds: [2]
   }]

2 个答案:

答案 0 :(得分:1)

    $(function () {
        var array =
      [{
        id: 1,
        name: 'Development',
        parentIds: [],
      },
      {
        id: 2,
        name: 'JavaScript',
        parentIds: [1]
      },
      {
        id: 3,
        name: 'React',
        parentIds: [2]
       },
       {
         id: 4,
         name: "Vue",
         parentIds: [2]
       }]

        var getId = function (arrayItems, id) {
            if (arrayItems) {
                for (var i in arrayItems) {
                    if (arrayItems[i].id == id) {
                        return arrayItems[i];
                    };
                    var found = getId(arrayItems[i].items, id);
                    if (found) return found;
                }
            }
        };

        var searchedItem = getId(array, 3);
        alert(searchedItem.name);
    });

答案 1 :(得分:0)

请参阅以下解决方案,我使用了lodash库和递归函数:

function foo(array, pid, res = [], did = []) {
  array = _.filter(array, (obj) => {
    if (_.includes(obj.parentIds, pid) || _.intersection(obj.parentIds, did).length) {
      res.push(obj.name);
      did.push(obj.id);
      return false;
    } else {
      return true;
    }
  });
  res = Array.from(new Set(res));
  did = Array.from(new Set(did));
  if (array.length >= did.length) {
    res.push(foo(array, pid, res, did));
  }
  return Array.from(new Set(res));
}