0

I'm getting an array from the backend that has an abritrary number of nested 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. 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. The property is equal to the "Name" property.

How can I do this in JavaScript?

asked Nov 6, 2019 at 15:32
0

1 Answer 1

3

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.

Working code for your sample data

answered Nov 6, 2019 at 15:37
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.