user1032531 user1032531 - 3 months ago 32
Javascript Question

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/

Answer

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);

Comments