gpt4 book ai didi

javascript - 如何从javascript中的对象获取特定的键值?

转载 作者:行者123 更新时间:2023-11-30 09:19:33 25 4
gpt4 key购买 nike

我有一个对象,我想创建一个具有特定键值的新对象,例如,

我有一个代码如下:

var objArray = [{
"firstname": "bbb",
"userName": "bbb1",
"title": "",
"created_by_user_id": "-1",
"enabled": "true",
"lastname": "AC",
"last_connection": "",
"password": "",
"manager_id": "0",
"id": "14",
"job_title": "job1",
"last_update_date": "2018-08-08 13:35:56.996"
},
{
"firstname": "aaa",
"icon": "icons/default/icon_user.png",
"creation_date": "2018-08-08 13:35:56.876",
"userName": "aaa1",
"title": "",
"created_by_user_id": "-1",
"enabled": "true",
"lastname": "AH",
"last_connection": "",
"password": "",
"manager_id": "0",
"id": "9",
"job_title": "job2",
"last_update_date": "2018-08-08 13:35:56.876"
}
]
for (var i = 0; i < obj.length; i++) {
objArray.push(obj[i]["id"]);
}
return objArray

我想创建一个像

这样的新对象
[{
"id": "14"
}, {

"id": "9",
}]

但是,我的结果是

[
"9",
"3"
]

我想得到一个对象的结果。感谢您的帮助。

提前致谢

最佳答案

只需将数组映射到仅包含指定键和值的新对象数组:

objArray.map(({ id }) => ({ id }));

这是一个例子:

var objArray = [{
"firstname": "bbb",
"userName": "bbb1",
"title": "",
"created_by_user_id": "-1",
"enabled": "true",
"lastname": "AC",
"last_connection": "",
"password": "",
"manager_id": "0",
"id": "14",
"job_title": "job1",
"last_update_date": "2018-08-08 13:35:56.996"
},
{
"firstname": "aaa",
"icon": "icons/default/icon_user.png",
"creation_date": "2018-08-08 13:35:56.876",
"userName": "aaa1",
"title": "",
"created_by_user_id": "-1",
"enabled": "true",
"lastname": "AH",
"last_connection": "",
"password": "",
"manager_id": "0",
"id": "9",
"job_title": "job2",
"last_update_date": "2018-08-08 13:35:56.876"
}
];

var processed = objArray.map(({ id }) => ({ id }));
console.log(processed);

关于javascript - 如何从javascript中的对象获取特定的键值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52612505/

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