Javascript - Create objects to push in array

Viewed 53

I've got two arrays where:

var arrayX = ["02/01/2014", "14/10/2014", "03/05/2014"];

var arrayY = [2, 10, 8];

I want to create 3 different objects, each one being:

 {x: "02/01/2014", y: 2} 
 {x: "14/10/2014", y: 10}
 {x: "03/05/2017", y: 8}

and create an array containing all the 3 objects.

So my code is:

  var data = [];

    for (var i = 0; i < arrayX.length; i++){
    
      var object = {x: arrayX[i], y: arrayY[i]};    
      data.push(object);
    
    }

But the result that I get is an array with just an object containing three X and three Y: result

var result = [{x:["02/01/2014","14/10/2014","03/05/2017"], y:[2,10,8]}];

What can I do?

2 Answers

Just make sure that arrayX and arrayY have the same lengths.

let arrayX = ["02/01/2014", "14/10/2014", "03/05/2014"];
let arrayY = [2, 10, 8];

let data = [];

for (let i in arrayX) {
    data.push({
        x: arrayX[i],
        y: arrayY[i]
    });
}

console.log('data: ' + JSON.stringify(data));

One way of merging it would by map over one of the arrays with referring to index in second:

const arrayX = ["02/01/2014", "14/10/2014", "03/05/2014"];
const arrayY = [2, 10, 8];

const data = arrayX.map((item, index) => ({
  y: arrayY[index],
  x: item,
}));

console.log(data);

it results:

[
  { y: 2, x: '02/01/2014' },
  { y: 10, x: '14/10/2014' },
  { y: 8, x: '03/05/2014' }
]

in the case of deeper nested structures, small modifications need to be applied to accommodate them. eg.

const arrayX = [ ["02/01/2014", "14/10/2014", "03/05/2014"] ];
const arrayY = [2, 10, 8];

const data = arrayX[0].map((item, index) => ({ 
.....
Related