Markus Hayner
Markus Hayner

Reputation: 2959

How to map two arrays to create objects?

I have two arrays and I need to create objects like {x: new Date(2019, 1, 1), y: 0} The result of my arrays looks like this

dates

Array [
  "2019, 1, 31",
  "2019, 2, 28",
  "2019, 3, 31",
]

monthlyTopUp

Array [
  0,
  50,
  0,
]

Now each index from first array needs to match the index from second array.

What I've tried returned me an array with other arrays inside

Array [
  Array [
    "2019, 1, 31",
    0,
  ],
  Array [
    "2019, 2, 28",
    50,
  ],
  Array [
    "2019, 3, 31",
    0,
  ],
]

The way I've done this:

const array = [dates, monthlyTopUp];
const data = array.reduce(
  (dates, topUp) => topUp.map((v, i) => (dates[i] || []).concat(v)), []
);
console.log(data)

Upvotes: 1

Views: 88

Answers (3)

enno.void
enno.void

Reputation: 6579

Or array.map

var arr1 = ["2019, 1, 31",  "2019, 2, 28",  "2019, 3, 31"];
var arr2 = [0, 50, 0];

var result = arr1.map((v, k) => {return {x:v,y:arr2[k]}})

console.log(result);

https://jsfiddle.net/fgo5wanh/

Upvotes: 1

Shubham Dixit
Shubham Dixit

Reputation: 1

You can use Array.prototype.reduce

let arr1 = ["2019, 1, 31",  "2019, 2, 28",  "2019, 3, 31"];
let arr2 = [0, 50, 0];

let final=arr1.reduce((acc,value,i)=>{
let tempobj={};

tempobj["x"]=new Date(value.replace(/\s/g, "").replace(/,/g, "-"));
tempobj["y"]=arr2[i];
acc.push(tempobj)
return acc;


},[])

console.log(final)

Upvotes: 1

NiVeR
NiVeR

Reputation: 9786

You can simply do it like this:

var arr1 = ["2019, 1, 31",  "2019, 2, 28",  "2019, 3, 31"];
var arr2 = [0, 50, 0];

var result = [];

for(var i = 0; i < arr1.length; i++){
    result.push({'x':arr1[i], 'y':arr2[i]});
}

console.log(result);

Upvotes: 2

Related Questions