Home > other >  Converting async responce of Array of Arrays into Object
Converting async responce of Array of Arrays into Object

Time:07-30

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}
    ]

CodePudding user response:

If you just want a flat array:

this.jobsService.jobsUpdated
  .pipe(
     pluck('parts'),
     map((parts)=> parts.flat())
  )

CodePudding user response:

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), [])
   })
);
  • Related