如何将对象的对象转换为对象数组?

时间:2013-01-26 19:43:05

标签: javascript jquery arrays json

我有一个外部文件 people.json 。如何使用json语法将其转换为javascript数组? 这是 people.json 内容:

{
"1":{
    "Name":"Jhon",
    "Surname":"Kenneth",
    "mobile":329129293,
    "email":"jhon@gmail.com"
},
"2":{
    "Name":"Thor",
    "Surname":"zvalk",
    "mobile":349229293,
    "email":"thor@gmail.com"
},
"3":{
    "Name":"Mila",
    "Surname":"Kvuls",
    "mobile":329121293,
    "email":"mila@gmail.com"
}
}

我想要一个这种格式的数组

var person = [
{ "name":"jhon" , "surname":"kenneth", "mobile":329129293, "email":"jhon@gmail.com"}, 
{ "Name":"Thor", "Surname":"zvalk", "mobile":349229293, "email":"thor@gmail.com" }, 
{ "Name":"Mila", "Surname":"Kvuls", "mobile":329121293, "email":"mila@gmail.com"}
];

我尝试了下一个代码,但它没有工作人员:

 var person;   
$.getJSON('people.json', function (json) {
person[]= json
});

顺便说一句,contacts.json文件在我的服务器中。

5 个答案:

答案 0 :(得分:4)

可以使用jQuery $.map()

var newArray=$.map( originalObject, function(item){
    return item;
})

DEMO:http://jsfiddle.net/qmfn2/

答案 1 :(得分:3)

试试这样:

$.getJSON('people.json', function (json) {
    var people = [];
    for (var key in json) {
        if (json.hasOwnProperty(key)) {
            var item = json[key];
            people.push({
                name: item.Name,
                surname: item.Surname,
                mobile: item.mobile,
                email: item.email
            });            
        }
    }

    // at this stage the people object will contain the desired output
});

答案 2 :(得分:1)

首先,您需要使用AJAX请求获取JSON文件。然后遍历收到的JSON对象并将每个属性添加到数组中。

function convertToArray (receivedObj) {
    var array = [], key;
    for (key in receivedObj) {
        array.push(receivedObj[key]);
    }
    return array;
}

$.getJSON('people.json', function (json) {
    var array = convertToArray(json);
});

希望这有帮助!

答案 3 :(得分:1)

像这样:

var array = $.map($.parseJSON(data), Object);

http://jsfiddle.net/mXFKL/

答案 4 :(得分:1)

$.getJSON('people.json', function (json) {
var array = convertToArray(json);
});