Search code examples
arraysangularobservabledata-conversion

Converting async responce of Array of Arrays into Object


I am trying to convert Array of Arrays that I get from Observable into single array of objects. This is my code:

    this.jobsService.jobsUpdated.pipe(
    map(
     (jobsData)=> {
      return jobsData.map(
        (job)=>{
        return  job.parts.map((part)=>{ return part })
        }
      )
     }
    )
   ).subscribe(
      (partsData)=>{
         console.log('partsdata', partsData)
      }
    );

This is the data format I am getting back:

    [
     [
       {partName:1, number:10, quantity: 100}
     ],
     [
       {partName:2, number:20, quantity: 200},
       {partName:3, number:30, quantity: 300}
     ],
     etc...
    ]

Please help to convert this data, hopefully in the pipe method, into :

    [
      {partName:1, number:10, quantity: 100},
      {partName:2, number:20, quantity: 200},
      {partName:3, number:30, quantity: 300}
    ]

Solution

  • Use reduce and no need of using inner map

    Why reduce? - To generate single output based on multiple inputs.

    this.jobsService.jobsUpdated.pipe(
        map((jobsData)=> {
          return jobsData.reduce(
            (acc, job)=>{
              acc.push(...job.parts)
              return acc;
            }
          , [])
        })
    );
    

    Alternatively concat can also be used

    this.jobsService.jobsUpdated.pipe(
       (jobsData)=> jobsData.reduce(
          (acc, job)=> acc.concat(job.parts), [])
       })
    );