将对象数组转换为2D数组

时间:2017-11-29 11:58:37

标签: javascript arrays

我想将一个对象数组转换为二维数组(数组数组)。我尝试使用map和Object.keys(),但我希望将每个对象的第一个值推入第一个数组,将每个对象的第二个值推入第二个数组等等......感谢您的回答。

好结果

[
  ['2', '5', '8', '10', '12'],
  ['4', '10', '16', '20', '24'],
  ['6', '15', '24', '30', '36'],
  ['10', '25', '40', '50', '60']
]

实际结果

[
  ['2', '4', '6', '10'],
  ['5', '10', '15', '25'],
  ['8', '16', '24', '40'],
  ['10', '20', '30', '50'],
  ['12', '24', '36', '60']
]



let obj = [
  {
    line1: '2',
    line2: '4',
    line3: '6',
    line4: '10'
  }, {
    line1: '5',
    line2: '10',
    line3: '15',
    line4: '25'
  }, {
    line1: '8',
    line2: '16',
    line3: '24',
    line4: '40'
  }, {
    line1: '10',
    line2: '20',
    line3: '30',
    line4: '50'
  }, {
    line1: '12',
    line2: '24',
    line3: '36',
    line4: '60'
  }
];

var output = obj.map(function(obj) {
  return Object.keys(obj).map(function(key) { 
    return obj[key];
  });
});

console.log(output);




2 个答案:

答案 0 :(得分:3)

您需要transfoming的索引并使用反向索引来访问结果集。



var array = [{ line1: '2', line2: '4', line3: '6', line4: '10' }, { line1: '5', line2: '10', line3: '15', line4: '25' }, { line1: '8', line2: '16', line3: '24', line4: '40' }, { line1: '10', line2: '20', line3: '30', line4: '50' }, { line1: '12', line2: '24', line3: '36', line4: '60' }],
    result = array.reduce((r, o, i) => {
        Object.keys(o).forEach((k, j) => (r[j] = r[j] || [])[i] = o[k]);
        return r;
    }, []);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




为了获得稳定的结果,您可以提前将键作为数组。



var array = [{ line1: '2', line2: '4', line3: '6', line4: '10' }, { line1: '5', line2: '10', line3: '15', line4: '25' }, { line1: '8', line2: '16', line3: '24', line4: '40' }, { line1: '10', line2: '20', line3: '30', line4: '50' }, { line1: '12', line2: '24', line3: '36', line4: '60' }],
    keys = ['line1', 'line2', 'line3', 'line4'],
    result = array.reduce((r, o, i) => {
        keys.forEach((k, j) => (r[j] = r[j] || [])[i] = o[k]);
        return r;
    }, []);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:1)

您还可以使用以下方法。

let obj = [
  {
    line1: '2',
    line2: '4',
    line3: '6',
    line4: '10'
  }, {
    line1: '5',
    line2: '10',
    line3: '15',
    line4: '25'
  }, {
    line1: '8',
    line2: '16',
    line3: '24',
    line4: '40'
  }, {
    line1: '10',
    line2: '20',
    line3: '30',
    line4: '50'
  }, {
    line1: '12',
    line2: '24',
    line3: '36',
    line4: '60'
  }
];

var output = [];
for(var i = 0; i < obj.length; i++){
   var index = 0;
   for(var values in obj[i]){
      if(output[index] == undefined){
        output[index] = [];
      }
      output[index].push(obj[i][values]);
      index++;
   }
}

console.log(output);