假设树形结构的数据如下:

const data = [
  {
    name: "A",
    type: "parent",
    children: [
      {
        name: "B1",
        type: "child"
      },
      {
        name: "B2",
        type: "child"
      }
    ]
  },
  {
    name: "C",
    type: "parent",
    children: [
      {
        name: "D1",
        type: "child"
      },
      {
        name: "D2",
        type: "child"
      },
      {
        name: "E1",
        type: "child"
      }
    ]
  }
];

我们可以使用递归的方式来将相同type值的对象放到一个数组里面:

const getTypeArray = (data, type) => {
  let result = [];
  data.forEach(item => {
    if (item.type === type) {
      result.push(item);
    }
    if (item.children && item.children.length > 0) {
      result = result.concat(getTypeArray(item.children, type));
    }
  });
  return result;
}

const parentArray = getTypeArray(data, 'parent');
const childArray = getTypeArray(data, 'child');

console.log(parentArray); // [{name: "A", type: "parent", children: [{name: "B1", type: "child"}, {name: "B2", type: "child"}]}, {name: "C", type: "parent", children: [{name: "D1", type: "child"}, {name: "D2", type: "child"}, {name: "E1", type: "child"}]}]
console.log(childArray); // [{name: "B1", type: "child"}, {name: "B2", type: "child"}, {name: "D1", type: "child"}, {name: "D2", type: "child"}, {name: "E1", type: "child"}]

在上面的代码中,我们定义了一个getTypeArray函数,它接受两个参数:data和type。其中data是树形结构的数据,type是我们要查找的type值。我们首先定义一个空数组result,用于存放查找结果。然后我们遍历data数组,如果当前元素的type值与参数type相等,就将当前元素push到result数组中。接着,我们判断当前元素是否有children属性,如果有,就递归调用getTypeArray函数,将返回的结果与result数组合并。最后,我们返回result数组作为结果。

我们可以调用getTypeArray函数两次,分别传入'parent'和'child'作为参数,得到parentArray和childArray两个数组,它们分别包含了所有type值为'parent'和'child'的元素

es6 递归将树形结构里面相同type值的对象 放到一个数组里面

原文地址: https://www.cveoy.top/t/topic/hlET 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录