Z
Z
zhdoon2019-04-08 08:35:46
JavaScript
zhdoon, 2019-04-08 08:35:46

How to convert an object with nested objects/arrays to an object with the same data using JavaScript?

There is an object with data of the form:

{
    main: Array(
                      {value : Array( [1], [2] ) },
                      {value : Array( [1], [2] ) }
    ),
    content: {
                  Array1( [1], [2: {key: value}] ), 
                  Array2( [1], [2] )
    },
   ...
}

Those. a given object contains children (object/array), which contain their children (object/array), and so on.
Is there a way in Javascript to convert such an object to pure JSON? A simple Stringify "clears" nested arrays.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Vasiliev, 2019-04-18
@qmax

Probably "simple Stringify" is a non-standard function and can do just about anything.
`JSON.stringify` does not clear any nested arrays.
The object in the example is written with invalid syntax.

V
Vitaly, 2019-04-18
@daruvayc0

Try digging into the reduce method. This may be a rather difficult method to understand, but there are a lot of cool things you can do with it.
Example: a function that "flattens" an array of the kind [1, 2, 3, [4, []], 8]] into a one-dimensional array [1, 2, 3, 4, 5 , 6, 7, 8].

function flatDeep(arr) {
 return arr.reduce((flattenArray, element) => {
   return Array.isArray(element) ? [...flattenArray, ...flatDeep(element)] : [...flattenArray, element]
 }, [])
}

console.log(flatDeep([1, 2, 3, [4, []], 8]])) // [1, 2, 3, 4, 5, 6, 7, 8]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question