简体   繁体   中英

Combine unknown sub-arrays of objects from an array of objects and filter it

a simpler way to re-create the output of this code, where if sub arr0 is not null, it then combines it and filter desired output by the key code .

Thank you in advance!

 let array = [ { id: 1, text: 'stuff1', arr0: [ {id:1, code: 'imacode1'}, {id:2, code: 'imacode2'}, ] }, { id: 2, text: 'stuff2', arr0: [ {id:3, code: 'imacode3'}, {id:4, code: 'imacode4'}, ] }, { id: 3, text: 'stuff3', arr0: [] } ] let arr = []; for(let i of array){ if(i.arr0.length !== 0){ arr.push(i.arr0) } } arr = arr.flat() for(let j of arr){ if(j.code === 'imacode2'){ let code = arr.filter(j=>j.code!=='imacode2') code = code.map(({code}) => code) console.log(code) } }

edit: added snippet

You oan use Array.flatMap() along with with Array.filter() to get the result you wish, first we use .flatMap() to create an array including all items in each arr0.

We then use .filter() to only include the desired items, using a custom (modifiable) filter function, in this case removing any item with a code of 'imacode2'.

 let array = [ { id: 1, text: 'stuff1', arr0: [ {id:1, code: 'imacode1'}, {id:2, code: 'imacode2'}, ] }, { id: 2, text: 'stuff2', arr0: [ {id:3, code: 'imacode3'}, {id:4, code: 'imacode4'}, ] }, { id: 3, text: 'stuff3', arr0: [] } ] // Change filter as desired.. const filterProc = ({id, code}) => code !== 'imacode2'; const result = array.flatMap(el => el.arr0 || []).filter(filterProc); console.log(result)
 .as-console-wrapper { max-height: 100% !important; top: 0; }

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