0

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

1
  • You should declare the obj inside the forEach function Commented Jul 12, 2021 at 16:59

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.