How to work with array which has object and nested array?

0 like 0 dislike
10 views
let user = [[5,12,2,22,'5,23'], { name:'abc', cost:'5', numbers:[1,5,33], count:{ props:4, area:7 } }]


As this array, create new array, and all values from the user array, something like this array should be res = [5,12,2,22,'of 5.23',cost,'5',numbers,1,5,33,count,props,4,area,7]; and it does not change the array user

I did it via check, created a new array and add all that is obiektem, then the array was removed through arra.isArray(), removed nested array and add it to another array but an associative array I've worked through a double for loop in and pulled out these values and keys in drugi array if it's right working method with a nested object? Or you can do everything easier?
by | 10 views

1 Answer

0 like 0 dislike
As this array, create new array, and all values from the user array, something like this array should be res = [5,12,2,22,'of 5.23',cost,'5',numbers,1,5,33,count,props,4,area,7];

I mean - you want all the elements of arrays and key/value objects, including embedded, were deployed in a one-dimensional array? Well, you can:

const toArray = val => val instanceof Array ? [].concat(...val.map(toArray)) : val instanceof Object ? [].concat(...Object.entries(val).map(([k, v]) => [ k, ...toArray(v) ])) : [ val ]; const res = toArray(user);
by

Related questions

0 like 0 dislike
1 answer
0 like 0 dislike
3 answers
0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
110,608 questions
257,186 answers
0 comments
33,864 users