0

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

2 Answers 2

1

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), [])
   })
);
Sign up to request clarification or add additional context in comments.

Comments

0

If you just want a flat array:

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

3 Comments

Not sure, how it will make sure to extract parts property only?
Yes, I forgot about this insignificant detail, I'll add it now
Thank you for your answer! I did not know about pluck. I will learn more about it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.