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

时间:2017-05-16 10:25:05

标签: javascript json parsing object key

我正在尝试从我的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"密钥名称之前选择房间名称:

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

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

roomName (PC)
roomName (classroom)

任何快速有效的方法吗?

4 个答案:

答案 0 :(得分:4)

你可以这样使用:

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

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

从这个问题中取出数组:Merge/flatten an array of arrays in JavaScript?

答案 1 :(得分:2)

您可以先使用Array.prototype.forEach()json.reservations数组进行迭代,然后再次r.resources进行迭代,如果满足表达式new RegExp(/roomName/, 'i').test(r.name),则生成Array.prototype.push()

请注意,json数组中包含小写"name": "roomName (classroom)"和大写"name": "RoomName (PC)",因此Regular Expression不会使用标记i检查区分大小写,最后RegExp.prototype.test()会检查roomName中是否有r.name

代码:

var 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": ""}]},
    result = [],
    regex = new RegExp(/roomName/, 'i');

json.reservations.forEach(function (r) {
  r.resources.forEach(function (r) {
    regex.test(r.name) && result.push({
      name: r.name
    });
  });
})

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:1)

你可以这样做:

{{1}}

答案 3 :(得分:0)

var jsonStr = "{ \"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\": \"\" } ] }";
var json = JSON.parse(jsonStr);
var array = [];  
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 resource = json.reservations[i].resources[j];
             if (resource.type === "room") {
                 if (array.indexOf("code")) {
                     array.push(resource.name);
                 }                                     
             }                                                                                         
         }

     }
}
 console.log(array);

在控制台中输出。请检查..

(2)[&#34; RoomName(PC)&#34;,&#34; roomName(教室)&#34;] 0:&#34; RoomName(PC)&#34; 1:& #34; roomName(教室)&#34;长度:2__proto__:数组(0)