gpt4 book ai didi

JavaScript - 从 JSON 对象中选取特定数据

转载 作者:行者123 更新时间:2023-12-02 07:21:46 25 4
gpt4 key购买 nike

我正在尝试从我的 JSON 响应中选择特定数据,如下所示;

{
"status": "success",
"reservations": [
{
"id": "26630",
"subject": "Subject",
"modifiedDate": "2017-05-16T06:05:12",
"startDate": "2017-05-16T08:00:00",
"endDate": "2017-05-16T09:45:00",
"resources": [
{
"id": "2408",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "3020",
"type": "realization",
"code": "realizationCode",
"name": "realizationName"
},
{
"id": "48",
"type": "room",
"code": "roomCode",
"parent": {
"id": "2",
"type": "building",
"code": "buildingCode",
"name": "buildngName"
},
"name": "RoomName (PC)"
}
],
"description": ""
},
{
"id": "21173",
"subject": "subjectName",
"modifiedDate": "2017-05-16T06:05:20",
"startDate": "2017-05-16T08:00:00",
"endDate": "2017-05-16T16:00:00",
"resources": [
{
"id": "3115",
"type": "realization",
"code": "realizationCode",
"name": "realizationName"
},
{
"id": "2584",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "52",
"type": "room",
"code": "roomCode",
"parent": {
"id": "2",
"type": "building",
"code": "buildingCode",
"name": "buildingName"
},
"name": "roomName (classroom)"
}
],
"description": ""
}
]
}

我已经使用 JSON.parse() 将其变成一个对象并使用 for-loops 遍历它;

var json = JSON.parse(data.responseText);

for (var i = 0; i < json.reservations.length; i++) {
if (json.reservations[i].resources != null) {
for (var j = 0; j < json.reservations[i].resources.length; j++) {

var reservations = json.reservations[i];
var resources = json.reservations[i].resources[j];

}
}
}

所以我需要在 "description" key name 之前选择房间名称:

"name": "roomName (PC)"
"name": "roomName (classroom)"

为了简单起见,我将 JSON 响应缩短了很多,但通常会有更多这样的房间名称。这个想法是从 JSON 响应主体中获取所有房间名称,并将它们推送到一个数组中,然后像这样按顺序打印出来;

roomName (PC)
roomName (classroom)

有什么快速有效的方法吗?

最佳答案

你可以这样使用:

const arrays = json.reservations
.filter(reservation => reservation.resources)
.map(reservation =>
reservation.resources.map(resource => resource.name)
)
;

const names = [].concat.apply([], arrays);

数组展平取自这个问题:Merge/flatten an array of arrays in JavaScript?

关于JavaScript - 从 JSON 对象中选取特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43998858/

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