将json multidimensional转换为数组javascript

时间:2014-04-02 08:09:50

标签: javascript arrays json multidimensional-array

我想将Json数据转换为数组Javascript,我可以像使用数组[0] [0]一样访问,有人可以帮助我。

[
    {
        "Login": "test1",
        "Nom": "test1",
        "Prenom": "test1p",
        "password": "124564",
        "Email": "test1@gmail.com"
    },
    {
        "Login": "test2",
        "Nom": "test2",
        "Prenom": "test2p",
        "password": "124564",
        "Email": "test2@gmail.com"
    }
]

我尝试了这段代码,但没有任何反应,我无法使用例如array [0] [1]访问数组中的特定数据(例如,我想拥有Nom)。

Code.js

var data = [
    {
        "Login": "test1",
        "Nom": "test1",
        "Prenom": "test1p",
        "password": "1267846",
        "Email": "test1@gmail.com"
    },
    {
        "Login": "test2",
        "Nom": "test2",
        "Prenom": "test2p",
        "password": "124494",
        "Email": "test2@gmail.com"
    }
];

function data_to_array(data) {
    var array = [];
    for (var key in data) {
        var value = data[key];
        if (typeof value === 'string') {
            array[key] = value;
        } else {
            array[key] = data_to_array(value);
        }
    }
    return array;
}

var array = data_to_array(data);
for(var i in array)
    console.log(array[i]);   

解析后,如果我尝试使用myArr [0] [1]访问它,它会显示为未定义。

2 个答案:

答案 0 :(得分:1)

var arr = [];

for (var i=0, len=data.length, tmp; i<len; i++) {
  tmp = [];
  for (var k in data[i]) {
    if (data[i].hasOwnProperty(k)) {
      tmp.push(data[i][k]);
    }
  }
  arr.push(tmp);
}

arr;
// [
//   ["test1","test1","test1p","124564","test1@gmail.com"],
//   ["test2","test2","test2p","124564","test2@gmail.com"]
// ]

如果可以依赖es5函数,可以使用Array.prototype.map和Object.keys

var arr = data.map(function(e) {
  return Object.keys(e).map(function(k) { return e[k]; });
});

arr;
// [
//   ["test1","test1","test1p","124564","test1@gmail.com"],
//   ["test2","test2","test2p","124564","test2@gmail.com"]
// ]

答案 1 :(得分:0)

你对数组和对象感到困惑。所有数组都是对象。但并非所有对象都是数组。您对包含对象的数组的错误理解使用“for..in”循环。 如果添加更多控制台语句并进行检查,则可以了解其工作原理。让我给出reqd。您的方案的解决方案。

var data = [
    {
        "Login": "test1",
        "Nom": "test1",
        "Prenom": "test1p",
        "password": "1267846",
        "Email": "test1@gmail.com"
    },
    {
        "Login": "test2",
        "Nom": "test2",
        "Prenom": "test2p",
        "password": "124494",
        "Email": "test2@gmail.com"
    }
];

function data_to_array(data) {
    var array = [];
    for (var i=0;i<data.length;i++) {
        var obj = data[i];
        array[i] = new Array();
        for(var key in obj) {
            array[i].push(obj[key]);
        }
    }
    return array;
}

var array = data_to_array(data);
console.log(array);