Reputation: 105
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.
Upvotes: 4
Views: 331
Reputation: 1
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
Upvotes: 4
Reputation: 222552
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);
Upvotes: 1