K
K
kachurinets2019-04-08 12:55:11
JavaScript
kachurinets, 2019-04-08 12:55:11

How to create a new array based on a nested array of objects?

I'm having some trouble creating a new array that will contain nested arrays of elements.

https://jsfiddle.net/4pus0b53/

I am looping and recursing to check nesting.
I need to get a similar object with the same nesting at the output. The output should be the same array, with the same nesting, but only with new names and possibly with some new fields.

let newArray = [
  {
  'label': 'root',
  'other': 'test field',
  'children': [
        {
            'label': 'Screening',
            'other': 'something other'
            'items': [
                {
                    "label": "Analyst",
                    "items": [
                        {
                            'label': "value2",
                            "filesId": "424"
                        },
                        {
                            "label": "value3",
                            "filesId": "320"
                        },
                        {
                            "label": "value4",
                            "filesId": "320"
                        }
                    ]
                },
            ]
        },
        ...
    ]
  }
]

How to write this new object correctly, do I need to write another one for the new array in my loop to check the nesting level, or is there some other way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-08
@kachurinets

function mapData(data) {
  return data.map((el) => {
    const override = {
      newProp: 'value',
    };
  
    if (el.children) {
      override.children = mapData(el.children);
    }
  
    return { ...el, ...override };
  });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question