I have one array of keys that I want to associate with all of the data returned from the API:
const arr = [
'cat',
'dog',
'horse',
]
const data_from_api = [
["cat_1",
"dog_1",
"horse_1"],
["cat_2",
"dog_2",
"horse_2"],
]
I want to create objects with the data that the keys area the values of this array and the values are the data that come from the API. How could I do this? Thanks in advance!
You could iterate over the api-data like this:
const arr =
['cat', 'dog', 'horse',]
const data_from_api = [
['cat_1','dog_1','horse_1'],
['cat_2','dog_2','horse_2'],
]
const result = {}
data_from_api.forEach((api, i) =>
// find array item (or create one, if not yet existant)
(result[arr[i]] || (result[arr[i]] = []))
// add current item
.push(data_from_api[i])
)
console.log(result);
The result would be:
{
cat: [["cat_1", "dog_1", "horse_1"]],
dog: [["cat_2", "dog_2", "horse_2"]]
}