Home > Enterprise >  how to extract all objects from nested arrays into one array in React
how to extract all objects from nested arrays into one array in React

Time:12-22

I have an array like this, which is the initial state of my useState:

Array [ (6) […], (6) […] ]
​
0: Array(6) [ undefined, {…}, {…}, … ]
​
1: Array(6) [ undefined, undefined, {…}, … ]

for example:

const[arr,setArr] = React.useState([
[
{label: "Beklam", id: 5032},
{label: "Dx6", id: 5052},
undefined,
undefined
],
[
{label: "item1", id: 50567},
{label: "item4", id: 505567},
{label: "item6", id: 50537},
{label: "itemA", id: 505647},
undefined,
undefined,
]
])

I want to make it like this:

[
{label: "Beklam", id: 5032},
{label: "Dx6", id: 5052},
{label: "item1", id: 50567},
{label: "item4", id: 505567},
{label: "item6", id: 50537},
{label: "itemA", id: 505647},
]

I should mention that undefined values came form inputs. in my case, it is possible to receive undefined and I should handle it.

this is from console.log output of browser. there's one array with two arrays inside of it. and each one of these 2 arrays have 6 elements inside of them. they can be more than 6. so the amount of elements are not static, as well as arrays.

the array can have multiple child arrays.

something like this:

0: undefined
1: undefined
2: Object { label: "Beklam", id: 5032 }
3: Object { label: "0/65%", id: 5061 }
4: undefined
5: undefined

I want to extract all objects inside of child arrays into one object. apparently extracting all values of those 2 arrays into a single array containing their objects.

and if possible, filtering undefined values and not showing them. instead of trying to use array.filter later on variable.

I actually haven't encountered a problem like this. so I don't really know how can I handle multi dimensional arrays.

CodePudding user response:

You can just use flatmap to make it into one dimensional array.

console.log(arr.flatMap((e) => e));

Or even simplier:

console.log(arr.flat());

And to filter out the undefined values:

console.log(arr.flatMap((e) => e.filter((f) => f !== undefined)));

CodePudding user response:

You can use flat to get it flattened into a single array.

You can use filter to remove the undefined entries.

const data = arr.flat(999).filter(Boolean)
  • Related