将json值添加到Array

时间:2016-01-10 17:17:05

标签: javascript jquery json

我有一个具有以下结构的json对象......

[{
    "staffId": 4,
    "forename": "Testf",
    "surname": "Tests",
    "location": "Testl",
    "phoneNumber": "00000000000",
    "email": "Teste"
}, {
    "staffId": 20,
    "forename": "Testf",
    "surname": "Tests",
    "location": "Testl",
    "phoneNumber": "00000000000",
    "email": "Teste"
}]

任何人都可以建议我如何将以下内容转换为嵌套数组,其结构如下所示......

var arr = [
    [4, "Testf", "Tests", "Testl", "00000000000", "Teste"],
    [20, "Testf", "Tests", "Testl", "00000000000", "Teste"]
]

3 个答案:

答案 0 :(得分:2)

试试这个:



var input = [{"staffId":4,"forename":"Testf","surname":"Tests","location":"Testl","phoneNumber":"00000000000","email":"Teste"},{"staffId":20,"forename":"Testf","surname":"Tests","location":"Testl","phoneNumber":"00000000000","email":"Teste"}];
var output = input.map(function(obj) {
  return Object.keys(obj).map(function(key) {
    return obj[key];
  }); 
});
document.getElementById('output').innerHTML = JSON.stringify(output);

<pre id="output"></pre>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你可以像下面这样做。希望这会对你有所帮助。

var item = [
            { "staffId": 4, "forename": "Testf", "surname": "Tests", "location": "Testl", "phoneNumber": "00000000000", "email": "Teste" }, 
            { "staffId": 20, "forename": "Testf", "surname": "Tests", "location": "Testl", "phoneNumber": "00000000000", "email": "Teste" }
           ];

var final=[];
$.each(item, function () {
    var arr=[];
    for (var prop in this) {
        arr.push(this[prop]);
    }
    final.push(arr);
})

console.log(final);

答案 2 :(得分:0)

虽然对象没有顺序,但我建议对键使用数组常量并迭代它。

var array = [{ "staffId": 4, "forename": "Testf", "surname": "Tests", "location": "Testl", "phoneNumber": "00000000000", "email": "Teste" }, { "staffId": 20, "forename": "Testf", "surname": "Tests", "location": "Testl", "phoneNumber": "00000000000", "email": "Teste" }],
    result = array.map(function (a) {
        return ['staffId', 'forename', 'surname', 'location', 'phoneNumber'].map(function (b) {
            return a[b];
        });
    });

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');