Let's say I have any array like:
a = ["name", "age"] and then an array of arrays like b = [["Alex", 20], ["Ari", 25], ..]
I want to make an array of object that get its keys from a and values from b
[{
name: "Alex",
age: 20
},
{
name: "Ari",
age: 25
}]
I tried the following:
for (const arr of b) {
Object.assign({}, arr)
}
which makes an object but doesn't use keys of array a.
const a = ["name", "age"]
const b = [["Alex", 20], ["Ari", 25]]
const output = b.map(item => {
return a.reduce((aggr, curr, i) => (aggr[curr] = item[i], aggr), {});
});
console.log(output);
However the code assumes the length of a always matches length of each item in b. Make sure to guard it properly.
In case you were pondering about the statement in parentheses (aggr[curr] = item[i], aggr), this is JavaScript's comma operator which executes all comma-delimited statements and returns the value of the last one - in this case aggr (which we need to return for next iteration of .reduce to aggregate the object).
If you want something in Python you can also try this.
my_list = []
a = ['name','age']
b = [['alex', 20], ['ari', 25], ['pete', 45], ['alf', 67]]
for person in b:
temp = {}
for i in range(len(a)):
temp[a[i]] = person[i]
my_list.append(temp)