转置JavaScript数组和对象

时间:2016-08-07 15:16:46

标签: javascript arrays object

如何转换JavaScript数组和对象?具体来说,我正在尝试将跟随xy数组/对象转换为新的所需x_newy_new数组/对象。

鉴于

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

所需

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

以下是我的尝试。

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/

1 个答案:

答案 0 :(得分:6)

轻松使用一些地图:

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

如果你不想要箭头功能,那就更加冗长了。

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

或者,如果您更喜欢循环方式,

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)