简体   繁体   中英

How to remove multiple empty array wrappers and just keep object

How to remove all the empty array wrappers ?

From this to

[[[{"type":"banana"},{"type":"orange"}]]]

To this

{"type":"banana"},{"type":"orange"}

If the the object as an array it should be maintained.

Use recursion -

 const input = [[[{"type":"banana"},{"type":"orange"}]]]; function flattenDeep(input) { return input.reduce((accu, val) => Array.isArray(val) ? accu.concat(flattenDeep(val)):accu.concat(val), []); } console.log(flattenDeep(input)); 

You can also use inbuilt function flat if you know the deepness of nesting.

 const input = [[[{"type":"banana"},{"type":"orange"}]]]; console.log(input.flat(2)); 

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