Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpose JavaScript array and object

How is a JavaScript array and object transposed? Specifically, I am trying to convert the follow x and y array/objects to the new desired x_new and y_new array/objects.

Given

var x=['x1','x2','x3'];
var y=[
    {name:'y1',data:['x1y1','x2y1','x3y1']},
    {name:'y2',data:['x1y2','x2y2','x3y2']}
];
console.log(x,y);

Desired

var new_x=[
    {name:'x1',data:['x1y1','x1y2']},
    {name:'x2',data:['x2y1','x2y2']},
    {name:'x3',data:['x3y1','x3y2']}
];
var new_y=['y1','y2'];
console.log(new_x,new_y);

Below is what I attempted.

var _x=[],_y=[];
for (var i = 0; i < y.length; i++) {
    _y.push(y[i].name);
    var data=[];
    for (var j = 0; j < y[i].data.length; j++) {
        data.push(y[i].data[j]);
    }
    _x.push({name:y[i].name,data:data});
}
console.log(_x,_y)

https://jsfiddle.net/fzf03c5t/

like image 552
user1032531 Avatar asked Aug 07 '16 15:08

user1032531


1 Answers

Easy using some maps:

var x = ['x1','x2','x3'];
var y = [
  {name:'y1', data:['x1y1','x2y1','x3y1']},
  {name:'y2', data:['x1y2','x2y2','x3y2']}
];
var new_x = x.map((str, i) => ({
  name: str,
  data: y.map(obj => obj.data[i])
}));
var new_y = y.map(obj => obj.name);
console.log(new_x, new_y);

If you don't want arrow functions it's a bit more verbose.

var x = ['x1','x2','x3'];
var y = [
  {name:'y1', data:['x1y1','x2y1','x3y1']},
  {name:'y2', data:['x1y2','x2y2','x3y2']}
];
var new_x = x.map(function(str, i) {
  return {
    name: str,
    data: y.map(function(obj) {
      return obj.data[i];
    })
  };
});
var new_y = y.map(function(obj) {
  return obj.name;
});
console.log(new_x, new_y);

Or, if you prefer your loop approach,

var x = ['x1','x2','x3'];
var y = [
  {name:'y1', data:['x1y1','x2y1','x3y1']},
  {name:'y2', data:['x1y2','x2y2','x3y2']}
];
var new_x = new Array(x.length),
    new_y = new Array(y.length);
for (var i = 0; i < x.length; i++) {
  var data = new Array(y.length);
  for (var j = 0; j < y.length; j++)
    data[j] = y[j].data[i];
  new_x[i] = {name: x[i], data: data};
}
for (var j = 0; j < y.length; j++)
  new_y[j] = y[j].name;
console.log(new_x, new_y)
like image 57
Oriol Avatar answered Oct 26 '22 11:10

Oriol