gpt4 book ai didi

javascript - 将 JSON 中的属性提取到 JavaScript 中的对象数组中

转载 作者:行者123 更新时间:2023-11-28 15:17:02 25 4
gpt4 key购买 nike

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 中,我只需要 ID , Name ,和gravatar值采用以下格式。

感谢任何帮助。

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',
}
];

最佳答案

只需迭代所有键,然后映射具有所需属性的新对象。

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>');

关于javascript - 将 JSON 中的属性提取到 JavaScript 中的对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33424844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com