如何将JSON对象转换为Javascript数组

时间:2014-06-19 09:49:41

标签: javascript jquery arrays json

链接到this questionthis one also,我想知道如何使用不同类型的JSON完成相同的操作:

这是我的JSON对象:

var myDb = {
    "04c85ccab52880": {
        "name": "name1",
        "firstname": "fname1",
        "societe": "soc1"
    },
    "04c95ccab52880": {
        "name": "name2",
        "firstname": "fname2",
        "societe": "soc2"
    },
    "048574220e2a80": {
        "name": "name3",
        "firstname": "fname3",
        "societe": "soc3"
     }
};

我的问题是我的JSON与他们的JSON不同,实际上我有一个数组数组。那么如何将其转换为Javascript数组?

var arr = [];

$.each( myDb, function( key, value ) {
    arr.push( value );    
});

console.log(user_list);

这种脚本似乎返回了我的3个不同的对象但是我的uid来自JSON?我怎么能得到它们?因为现在我的钥匙是0,1,2而不再是我的uid。

有什么想法吗?感谢

2 个答案:

答案 0 :(得分:6)

工作JSFIDDLE

JS代码:

//var arr = [];
var myDb = {
    "04c85ccab52880": {
        "name": "name1",
        "firstname": "fname1",
        "societe": "soc1"
    },
    "04c95ccab52880": {
        "name": "name2",
        "firstname": "fname2",
        "societe": "soc2"
    },
    "048574220e2a80": {
        "name": "name3",
        "firstname": "fname3",
        "societe": "soc3"
     }
};

$.each( myDb, function( key, value ) {
    //arr.push( value );    
    console.log("key => "+key);//will output: 04c85ccab52880 and all such
    $.each( value, function( ky, val ) {
        console.log('ky => '+ky);//will output: name, firstname, societe
        console.log('val => '+val);//will output: name1, fname1, soc1
    });    
});

答案 1 :(得分:1)

如果你想用钥匙转换它们。我建议如下

var mapped = Object.keys( myDb  ).map(function( uid ){
    return (myDb[uid ].uid = uid ) && myDb[uid ];
});

对于数组中的值,示例mapped[0]具有值:

{
    "name": "name1",
    "firstname": "fname1",
    "societe": "soc1",
    "uid": "04c85ccab52880"
}