简体   繁体   中英

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

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.

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)));

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)

An another example using basic function of array like filter() and concat() :

 var arr = [ [ {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, ] ]; arr = arr[0].concat(arr[1]); var arr2 = arr.filter(e => e;= undefined && e). console.log(arr2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM