递归获取所有孩子 [英] Recursively get all children

查看:38
本文介绍了递归获取所有孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从嵌套对象中递归获取所有子项.我已经写了一个函数来完成它(有点)但我认为它可以改进.

I need to recursively get all children from a nested object. I already wrote a function that does it (kinda) but I think it can be improved.

我怎样才能让它更短更干净?

我已经包含了我用于测试的数据以及我编写的需要改进的函数.

I have included the data I'm using for testing as well as the function I wrote that needs improvement.

let data = [{
    id: 1,
    child: {
      id: 2,
      child: {
        id: 3,
        child: {
          id: 4,
          child: null
        }
      }
    }
  },
  {
    id: 5,
    child: {
      id: 6,
      child: null
    }
  }
];


// function

for (let cat of data) {
  cat.children = getCategoryChild(cat);
  console.log(cat.children)
}

function getCategoryChild(cat) {
  let t = [];

  if (cat.child != null) {
    t.push(cat.child);

    let y = getCategoryChild(cat.child);
    if (y.length > 0) {
      for (let i of y) {
        t.push(i)
      }
    }
  }

  return t;
}

预期输出:

[{id: 1, children: [{id: 2}, {id: 3}, {id: 4}]}, {id: 5, children: [{id: 6}]}]

推荐答案

假设每个类别只有一个子项

assuming that each category only ever has one child

编辑以符合预期的结果...

edited to adhere to the expected result...

function iterChildren(cat) {
  let c = cat, children = [];

  while (c.child) {
    children.push({id: c.child.id});
    c = c.child;
  }

  return {id: cat.id, children: children};
}

let newData = data.map(iterChildren);

这篇关于递归获取所有孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆