js使用多种方法取出嵌套对象数组中的所有 children 的值

文章介绍了如何使用递归函数、reduce以及flatMap方法在JavaScript中实现对包含children属性的嵌套对象数组进行深度优先遍历,以获取所有子项的数组。这三个方法都有效地遍历了整个结构,避免无限循环的风险。
摘要由CSDN通过智能技术生成

数据源:

const items = [
  {
    id: 1,
    name: "item1",
    children: [
      {
        id: 11,
        name: "item11",
        children: [
          {id: 111, name: "item111"},
          {id: 112, name: "item112"}
        ]
      },
      {
        id: 12,
        name: "item12",
        children: [
          {id: 121, name: "item121"},
          {id: 122, name: "item122"},
          {id: 123, name: "item123"}
        ]
      }
    ]
  },
  {
    id: 2,
    name: "item2",
    children: [
      {id: 21, name: "item21"},
      {id: 22, name: "item22"}
    ]
  }
];

方法:

 

1.使用递归函数进行深度优先遍历

function getAllChildren(items) {
  let children = [];
  items.forEach(item => {
    children.push(item);
    if (item.children) {
      children = children.concat(getAllChildren(item.children));
    }
  });
  return children;
}
// 调用函数
const allChildren = getAllChildren(items);
console.log(allChildren);

 

2.使用 reduce 递归方法进行深度优先遍历

function getAllChildren(items) {
  return items.reduce((acc, item) => {
    const { children = [], ...rest } = item;
    return [...acc, rest, ...getAllChildren(children)];
  }, []);
}
// 调用函数
const allChildren = getAllChildren(items);
console.log(allChildren);

3.使用 flatMap 方法进行深度优先遍历

function getAllChildren(items) {
  return items.flatMap(item => {
    const { children = [], ...rest } = item;
    return [rest, ...getAllChildren(children)];
  });
}
// 调用函数
const allChildren = getAllChildren(items);
console.log(allChildren);

这些方法都会遍历整个嵌套对象数组,并返回包含所有 children 的数组。请注意,使用递归方法时要小心,确保没有无限循环。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南北极之间

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值