从JSON中将属性从JavaScript中提取到对象数组中

时间:2015-10-29 21:22:15

标签: javascript json

JSON用户列表

{
    "1": {
        "id": "1",
        "name": "jasondavis",
        "first_name": "Jason",
        "last_name": "Davis",
        "is_admin": "1",
        "gravatar": "31b64e4876d603ce78e04102c67d6144"
    },
    "1702c3d0-df12-2d1b-d964-521becb5e3ad": {
        "id": "1702c3d0-df12-2d1b-d964-521becb5e3ad",
        "name": "Jeff",
        "first_name": "Jeff",
        "last_name": "Mosley",
        "is_admin": "1",
        "gravatar": "5359bf585d11c5c35602f9bf5e66fa5e"
    }
}

JS对象数组格式我需要它......

从上面的JSON我只需要下面格式的IDNamegravatar值。

任何帮助表示感谢。

var userItemsArray = [
    {
        id: 0,
        name: 'None',
        gravatar: 'http://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=36&d=identicon&r=PG',
    },
    {
        id: 1,
        name: 'Jason Davis',
        gravatar: 'http://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=36&d=identicon&r=PG',
    },
    {
        id: 2,
        name: 'Item 2',
        gravatar: 'https://avatars3.githubusercontent.com/u/7988569?v=3&s=40',
    }
]; 

1 个答案:

答案 0 :(得分:4)

迭代所有键,然后使用想要的属性映射新对象。



var userList = {
        "1": {
            "id": "1",
            "name": "jasondavis",
            "first_name": "Jason",
            "last_name": "Davis",
            "is_admin": "1",
            "gravatar": "31b64e4876d603ce78e04102c67d6144"
        },
        "1702c3d0-df12-2d1b-d964-521becb5e3ad": {
            "id": "1702c3d0-df12-2d1b-d964-521becb5e3ad",
            "name": "Jeff",
            "first_name": "Jeff",
            "last_name": "Mosley",
            "is_admin": "1",
            "gravatar": "5359bf585d11c5c35602f9bf5e66fa5e"
        }
    },
    userItemsArray = Object.keys(userList).map(function (k) {
        return {
            id: userList[k].id,
            name: userList[k].name,
            gravatar: userList[k].gravatar
        };
    });
document.write('<pre>' + JSON.stringify(userItemsArray, 0, 4) + '</pre>');
&#13;
&#13;
&#13;