如何使用递归取出指定条件的数组,并且返回原结构?

原来结构:

   [{
      id:1,
      type: '1',
      name: '测试1',
      children: [
        {
          id:2,
          type: '2',
          name: '测试2',
          children: [
          {
            id:3,
            type: '3',
            name: '测试3',
          }
          ]
        }
      ]
    }]

我想要得到type不等3的数据
如:

  [{
      id:1,
      type: '1',
      name: '测试1',
      children: [
        {
          id:2,
          type: '2',
          name: '测试2',
        }
      ]
    }]
阅读 1.8k
4 个回答

你试试这个方法:

function filterByType(arr) {
  return arr.map(obj => {
    if (obj.type === '3') {
      return undefined;
    } else if (obj.children) {
      obj.children = filterByType(obj.children).filter(Boolean);
    }
    return obj;
  });
}

针对每一层的 children 进行 type !== 3 的方式过滤,然后重新赋值给当前层的 children 就好了,这个应该不难。

本文参与了SegmentFault 思否面试闯关挑战赛,欢迎正在阅读的你也加入。
function deepFilter(arr, cb) {
  return arr.reduce((res,v) => {
   cb(v) && res.push({...v, children: deepFilter(v.children||[], cb)})
   return res;
  }, [])
}

deepFilter([{
  id:1,
  type: '1',
  name: '测试1',
  children: [
    {
      id:2,
      type: '2',
      name: '测试2',
      children: [
        {
          id:3,
          type: '3',
          name: '测试3',
        }
      ]
    }
  ]
}], v => v.type != 3)
function filterDeep(list, callback) {
    if (Array.isArray(list)) {
        var arr = [];
        for (var i = 0; i < list.length; ++i) {
            var item = list[i];
            if (callback(item, i, list)) return;
            item = filterDeep(item, callback);
            if (item != null) arr.push(item);
        }
        return arr;
    }
    if (typeof list === "object" && list !== null) {
        var obj = new list.constructor();
        for (var key in list) {
            var value = list[key];
            if (callback(value, key, list)) return;
            value = filterDeep(value, callback);
            if (value != null) obj[key] = value;
        }
        return obj;
    }
    return list;
}
console.log(filterDeep([{
    id: 1,
    type: '1',
    name: '测试1',
    children: [{
        id: 2,
        type: '2',
        name: '测试2',
        children: [{
            id: 3,
            type: '3',
            name: '测试3',
        }]
    }]
}], function (value, key) {
    return key === "type" && value === "3";
}));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题