【问题标题】:How to loop through a huge json with same key names如何遍历具有相同键名的巨大 json
【发布时间】:2021-10-08 04:26:22
【问题描述】:

我有一个巨大的 json 文件,结构如下:

    name: 'xxx',
    worth: [123, 456, 789]
    children: [
       {name: 'xxx',
       worth: [987, 654, 321],
       children: [
          {name: 'xxx',
          worth: [213, 546, 879],
          children: []}
       },
       {name: 'xxx',
       worth: [987, 654, 321],
       children: [
          name: 'xxx',
          worth: [213, 546, 879],
          children: []
       }],
    ]

孩子的数量可以达到 10 层深度。 我创建了一个显示名称和价值的角度组件,并将子项作为输入以使用子项的名称和价值再次调用自己,但使用这种方法我得到最大堆栈大小错误。

如何编写一个函数,可以循环遍历这个 json 直到 children 数组为空,并在途中显示所有它们的名称和价值? 这尖叫递归,但我无法管理......

【问题讨论】:

  • 显示角度分量...
  • 预期的输出应该是什么?
  • 我实际上想列出所有的名字、价值和孩子,直到没有孩子出现为止。
  • 类似这样的东西:stackblitz.com/edit/js-d3y5tm

标签: arrays json angular typescript


【解决方案1】:

假设您的根对象代表一个子对象,您的代码将如下所示:

const child = {
  name: "xxx1",
  worth: [123, 456, 789],
  children: [
    {
      name: "xxx2",
      worth: [987, 654, 321],
      children: [
        {
          name: "xxx3",
          worth: [213, 546, 879],
          children: []
        }
      ]
    },
    {
      name: "xxx4",
      worth: [987, 654, 321],
      children: [
        {
          name: "xxx5",
          worth: [213, 546, 879],
          children: []
        }
      ]
    }
  ]
};

const sum = (arr) => arr.reduce((a, b) => a + b, 0);

function process_child(child, result) {
  const { name, worth, children } = child;
  result.push({ name, worth: sum(worth) });

  for (const c of children) {
    process_child(c, result);
  }

  return result;
}

const children = process_child(child, []);
console.table(children);

这里,process_child 是一个函数,它接收一个 child 和一个结果列表(最初为空)。它在遍历所有嵌套子项时填充结果列表。最终结果是一个结构为 {name, worth} 的对象数组,然后您可以以任何您希望的方式使用它。

这不是 Angular 特有的问题,实际上您只是希望 Angular 组件成为此函数返回的数据的被动消费者。

这是CodeSandbox 上的一个有效执行,其结果以 JSON 形式简单地显示在页面上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-11
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 2012-12-29
    • 2014-11-08
    相关资源
    最近更新 更多