简体   繁体   English

如何在 JavaScript 中循环任意数量的嵌套 arrays 数组

[英]How to loop over an array of arbitrary number of nested arrays in JavaScript

I'm getting an array from the backend that has an abritrary number of nested arrays.我从后端获取了一个数组,该数组具有嵌套的 arrays 的任意编号。 Each array element is a company and may or may not have a Children property which is again an array of companies that each may or may not have child companies.每个数组元素都是一个公司,可能有也可能没有Children属性,它又是一个公司数组,每个可能有也可能没有子公司。 For example:例如:

[ 
   { 
      Name:"Company X",
      Children:[ 
         { 
            Name:"Company XY"
         },
         { 
            Name:"Company XZ",
            Children:[ 
               { 
                  Name: "Company XZY"    // third level of nested arrays, can be an abritrary number of levels
               }
            ]
         }
      ]
   },
   { 
      Name:"Company Y",
      Children:[ 
         { 
            Name:"Company YZ"
         }
      ]
   }
]

I have to add a "Label" property to each company object.我必须为每个公司 object 添加一个“标签”属性。 The property is equal to the "Name" property.该属性等于“名称”属性。

How can I do this in JavaScript?如何在 JavaScript 中做到这一点?

Gotta use recursion here.必须在这里使用递归。

function addLabelRecursive(company) {
  if (company.Name) {
    company.Label = company.Name;
  }
  if (company.Children) {
    company.Children.forEach(addLabelRecursive);
  }
}

This function adds a label and if children exist runs itself for each child.这个 function 添加了一个 label 并且如果存在孩子,则为每个孩子运行自己。

Working code for your sample data示例数据的工作代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM