Javascript - 将dict转换为数组

时间:2015-05-26 13:07:42

标签: javascript

我有一个以下要转置的词:

dict = {
         'column1': [1, 2, 3],
         'column2': [4, 5, 6],
         'column3': [7, 8, 9]
        }

分为:

transposed_array = [
                    [1, 4, 7],
                    [2, 5, 8],
                    [3, 6, 9]
                  ]

3 个答案:

答案 0 :(得分:1)

这是一个解决方案(针对非方形矩阵更新):

var dict = {
     'column1': [1, 2, 3],
     'column2': [4, 5, 6],
     'column3': [7, 8, 9]
}
var keys = Object.keys(dict);
var transposedMatrix = dict[keys[0]].map(function(col,i){  
  return keys.map(function(_,j){ return dict[keys[j]][i] })
});

Demonstration

请注意,此代码假定 do 对象具有有序键,在所有已知的ES实现和is now normalized by ES6中一直如此。

答案 1 :(得分:1)

var dict = {
         'column1': [1, 2, 3],
         'column2': [4, 5, 6],
         'column3': [7, 8, 9]
        };
var transposed_array =[];
for (key in dict){
    transposed_array.push(dict[key]);

}
console.log(transposed_array);  

Demo
更新

var dict = {
         'column1': [1, 2, 3],
         'column2': [4, 5, 6],
         'column3': [7, 8, 9]
        };
var transposed_array =[];
for (key in dict){
    transposed_array.push(dict[key]);

}
function transposeArray(array){

    var newArray = [];
    for(var i = 0; i < array.length; i++){
        newArray.push([]);
    }

    for(var i = 0; i < array.length; i++){
        for(var j = 0; j < array[i].length; j++){
            newArray[j].push(array[i][j]);
        }
    }

    return newArray;
}
console.log(transposeArray(transposed_array));  

Demo

答案 2 :(得分:1)

基本上首先找到密钥的共享部分,然后在排序后重新分配数组。结果是数字顺序,如果数字,否则维持订单。

var dict = {
        'column3': [7, 8, 9],
        'column2': [4, 5, 6],
        'column1': [1, 2, 3]
    },
    keys = Object.keys(dict),
    samePart = keys.reduce(function (a, b) {
        var i = 0, l = Math.min(a.length, b.length);
        while (i < l && a[i] === b[i]) { i++; }
        return a.substr(0, i);
    }),
    otherPart = keys.map(function (e) { return e.slice(samePart.length); }).sort(function (a, b) { return a - b; }),
    transposedMatrix = [].map.call(otherPart, function (col, i) { return dict[samePart + col].map(function (_, j) { return dict[samePart + col][j]; }); });