4

I have a problem that I can't figure out. Basically I receive two arrays with coordinates in them:

const xData = [1, 3, 5, 7, 9];
const yData = [2, 4, 6, 8, 10];

I need to combine these two arrays into an object like so:

var data = [{ x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 7, y: 8 }, { x: 9, y: 10 }];

I combined the two arrays to get the coordinates together

const xData = [1, 3, 5, 7, 9];
const yData = [2, 4, 6, 8, 10];

var coords = xData.map((v, i) => { return [v, yData[i]]; });

console.log(coords);

I'm not sure how to take this new array and turn it into an object assigning x and y keys to each to element of the object.

Jay Joshi
  • 858
  • 7
  • 24
ees3
  • 85
  • 9

2 Answers2

3

First way is to map your intermediate array to an array of objects

const xData = [1, 3, 5, 7, 9];
const yData = [2, 4, 6, 8, 10];

var coords = xData.map((v, i) => [v, yData[i]]).map(([x, y]) => ({x, y}));

console.log(coords);

as a bonus, see the shorthand for your current map callback

second (preferred, unless you also want the array version as well) way is to map directly to an object

const xData = [1, 3, 5, 7, 9];
const yData = [2, 4, 6, 8, 10];

var coords = xData.map((x, i) => ({ x, y:yData[i]}));

console.log(coords);

You may need to read up on destructuring assignment

Jaromanda X
  • 1
  • 4
  • 64
  • 78
1

const xData = [1, 3, 5, 7, 9];
const yData = [2, 4, 6, 8, 10];
 

var coords = xData.map((v, i) => { return [v, yData[i]]; }).map(([x, y]) => ({x, y}));
console.log(coords);
Sajeetharan
  • 203,447
  • 57
  • 330
  • 376