Home > Software design >  Combine unknown sub-arrays of objects from an array of objects and filter it
Combine unknown sub-arrays of objects from an array of objects and filter it

Time:11-03

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)
  }
}
    
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

edit: added snippet

CodePudding user response:

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).map(({code}) => code);
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related