0

I have two arrays, one is dates and the other is prices. I need to create one JS object containing the intersection of these two.

It needs to look like this:

{ date: "2018-01-01", price: 82 }

or

{ date: date[0], price: price[0]}

... for 250 rows.

I know that I can use Object.assign.apply to combine objects, but then I got an object looking like:

{"2018-01-01": 82 } 

without the keys. So how do I format the keys?

Thanks!

1
  • 2
    Can you provide sample input and expected output? Commented Aug 8, 2018 at 15:45

3 Answers 3

1

You can .map() it and ... spread it to combine like:

let dates = [{date:'20-jan-2017'},{date:'20-dec-2016'}];
let prices = [{price:200}, {price:300}]

let combined = dates.map((date, key) => { return {...date, ...prices[key]}})

console.log(combined);

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

Comments

0

If your arrays are the same length, which I assume they are then you can just iterate over them and add both elements into an object array.

let output = [];
for(let i = 0; i < arrLen; i++){
  output.push({
    date: arr1[i],
    price: arr2[i]
  });
}

Comments

0

Assuming that both arrays have the same size you could do

const prices = [...] // an existing array
const dates = [...] // another array with the same length
const newArray = dates.map((date, i) => ({ date, price: prices[i] }))

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.