简体   繁体   中英

How to convert an object with two arrays in an array of object?

I have two arrays like:

descriptionList: ["First", "Second", "Last"]

statusList: ["Jon", "Jim", "Den"]

I want to create a list of objects, like this:

  "subtasks": [
   {
     "description": First,
     "status": "Jon"
   },
   {
     "description": Second,
     "status": "Jim"
   },
  ....
],

Lists can have more than 3 elements.

What I have tried is this:

var result = {};
descriptionList.forEach((key, i) => result[key] = statusList[i]);
console.log('result', result);

What it prints is this one, which is not what I want:

{ First: "Jon", Second: "Jim", Last: "Den" }

You can zip both arrays and use map to create the expected structure:

 function zip(arr1, arr2) { return Array(Math.max(arr1.length, arr2.length)).fill(0).map((_, idx) => ([arr1[idx], arr2[idx]])); } const data = { descriptionList: ["First", "Second", "Last"], statusList: ["Jon", "Jim", "Den"] }; const result = { subtasks: zip(...Object.values(data)).map(el => ({ description: el[0], status: el[1] })) }; console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM