S
S
sumrakx2019-01-17 02:43:32
JavaScript
sumrakx, 2019-01-17 02:43:32

How to expand nested array?

There is an object that stores data in which there are nested child arrays. I want all nested child arrays to lie at the same level in the new array.
5c3fc142768ca731915520.png
Any ideas how to do this - only recursive deployment comes to mind?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
H
hack504, 2019-01-17
@sumrakx

Only recursively.

const nested = {
  id: 1,
  children: [
    { id: 2 },
    { id: 3,
      children: [{ id: 5 }, { id: 6 }]
    },
    { id: 4 }
  ]
}

const flatten = function(obj) {
  const array = Array.isArray(obj) ? obj : [obj];
  return array.reduce(function(acc, value) {
    acc.push(value);
    if (value.children) {
      acc = acc.concat(flatten(value.children));
      delete value.children;
    }
    return acc;
  }, []);
}

flatten(nested); // => [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 5 }, { id: 6 }, { id: 4 } ]

A
akavato, 2019-01-17
@akavato

If I understand correctly, you need to make a flat array.
look at the implementation of flatten and flattenDeep in lodash
or here ready: MDN

A
Alexander Shumigin, 2021-03-05
@pioner92

I don't know how efficient it is, but it will expand any nesting
for an array of strings or numbers, which will become strings in the final array

arr.toString().split(',')
arr.join().split(',')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question