I need to turn two JavaScript arrays into a list of objects. One of the input arrays represents the keys of the output object and the other contains its values (alongside some other information, not relevant to this question).
Example data:
let theKeys = ['firstName', 'lastName', 'city'];
let theValues = [{data: [['John', 'Smith', 'New York'],
['Mike', 'Doe', 'Chicago'],
...
],
otherStuff: ...}
];
Desired output for above:
output = [{
firstName: 'John',
lastName: 'Smith',
city: 'New York'
},
{
firstName: 'Mike',
lastName: 'Doe',
city: 'Chicago',
},
...
]
(This is just an example, my actual data comes from REST responses and can vary in content and length. I'm working with a Vue app that displays tabular data.)
My existing code, below, works for small amounts of data but makes all browsers crash or hang for larger amounts of data.
return this.theValues.flatMap(results => {
let jsonified = [];
for (let v = 0; v < results.theValues.length; v++) {
let singleJson = {};
for (let k = 0; k < this.theKeys.length; k++) {
let key = this.theKeys[k];
singleJson[key] = results.data[v][k];
}
jsonified.push(singleJson);
}
return jsonified;
});
For as few as a couple thousand results, this takes minutes to run. How can I make it faster? Is there some operation I'm missing that will allow me to avoid the nested for loop?