So I have an array of arrays which are rows in a table and I'd like to convert that to an array of objects. I have a columns array so I know what the keys will be, and of course the length is obviously the same. I know how to do this traditionally with a for loop, but was wondering how to do this with reduce or possible another more succinct way.
let columnArr = ["Name", "Group", "Tier"];
let twoDArryOfArrs = [
["Fred", "1FAKnock", "1a"],
["Brenda", "2GPvoge", "1a"],
["Francis", "67Gruz", "1a"],
["Arnold", "1FAKnock", "2b"],
["Candice", "67Gruz", "1a"],
["Larry", "1GTAFQT", "4a"],
["Tony", "2GPvoge", "2c"],
["Ronnie", "2GPvoge", "3a"]
];
function convert2dArryToArrOfObjects(arr2d, colArr) {
let obj = {},
resultArr = [];
for (let i = 0; i < arr2d.length; i++) {
let innerArr = arr2d[i];
for (let j = 0; j < innerArr.length; j++) {
obj[colArr[j]] = innerArr[j];
}
resultArr.push(obj);
obj = {};
}
return resultArr;
}
const output = convert2dArryToArrOfObjects(twoDArryOfArrs, columnArr);
console.log(output);