Better way of mapping nested arrays in javascript?

  Kiến thức lập trình

I have an object

 const resp = [
  {
     "projectId":"26549b0e-bf31-db41-f2c0-734be4220846",
     "projectName":"Project 1",
     "jobs":[
       {
           "jobId":"6bf06da2-27e3-11ef-a6d1-0242ac124444",
           "id":4,
           "title":"Job 4"
        }
     ]
  },
  {
     "projectId":"71e129b2-9b73-4627-8712-c0e1a74251a0",
     "projectName":"Project 2",
     "jobs":[
        {
           "jobId":"6beea189-27e3-11ef-a6d1-0242ac120003",
           "id":1,
           "title":"Job 1"
        }
     ]
  }
];

And the output I need is

[
    {
      id: 4,
      jobId: "6bf06da2-27e3-11ef-a6d1-0242ac124444",
      key: 4,
      title: "Job 4"
    },
    {
      id: 1,
      jobId: "6beea189-27e3-11ef-a6d1-0242ac120003",
      key: 1,
      title: "Job 1"
    },
]

My solution works OK and it is

const jobsToMap = []

resp.forEach((project) => {
  project.jobs.forEach((job)=>{
    jobsToMap.push(job)
  })
});

const mappedJobs = jobsToMap.map((job) => {
  return {...job, key: job.id};
})

Is there any better/neater way, for example without nesting for each and pushing values to an array and then doing mapping separately so I could have a variable with all the logic returning new array?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT