Reputation: 1858
I have these 2 arrays:
productsForSale = ['eggs', 'eggs', 'bread', 'milk'];
soldPrice = [2.70, 2.50, 1.97, 3.29];
yes, the values of the first 2 elements ("eggs") are different but that's meant to be for this question. Now I want to create an array of objects that will look like this:
[
{
eggs: 2.70
},
{
eggs: 2.50
},
{
bread: 1.97
},
{
milk: 3.29
}
]
So far I have this code:
var obj = {};
var arr = [];
productsForSale.forEach((key, i) => {
obj[key] = soldPrice[i];
arr.push(obj);
});
But I don't get the expected output. Can anyone point me in the right dirrection? Thanks
Upvotes: 0
Views: 37
Reputation: 5947
You can use map().
const productsForSale = ["eggs", "eggs", "bread", "milk"];
const soldPrice = [2.7, 2.5, 1.97, 3.29];
const output = productsForSale.map((el, i) => ({ [el]: soldPrice[i] }));
console.log(output);
Upvotes: 1