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);