简体   繁体   中英

How to access json key value from ajax success?

I want to access the logs of the data I am getting from the ajax response. I want to create it as an array so that I can access all the logs. But right now whenever I parse the data, it takes it as a single object value.

In the data there is only one _id=1. I want to access the logs.

[
 {
   "_id": "1",
   "qos": "Access",
   "date": "2020-02-26",
   "logs": [
     {
       "qos": "Access",
       "date": "2020-02-26",
       "hour": 23,
       "cellName": "A11" 
     },
     {
       "qos": "Access",
       "date": "2020-02-26",
       "hour": 21,
       "cellName": "A12" 
     }
     {
        similar for entries
     },{}
}
] 

$.ajax({
       type: 'POST',
       async: 'false',
       url: '/data_from_datastore',
       contentType: 'application/json',
       data: JSON.stringify(sendDate1),
       success: function (data) {
           debugger;

               data = JSON.parse(data); // Here I want to create an array of all the log values

I want to read the data as:

 [
     {
       "qos": "Access",
       "date": "2020-02-26",
       "hour": 23,
       "cellName": "A11" 
     },
     {
       "qos": "Access",
       "date": "2020-02-26",
       "hour": 21,
       "cellName": "A12" 
     }
     {
        similar for entries
     }
}
] 

Is there any way to parse only the log part?

I don't think you can parse only the piece of data. But you can use array.reduce, like

const logs = data.reduce((result, item) => { return [...result, item.logs] }, []);

Or some not ECMA2015 version, like

var logs = [];
data.forEach(function(item){ logs.push(item.logs); });

Or if you need only the first item of the data array -

var logs = JSON.parse(data)[0].logs;

尝试

 result = JSON.parse(data)[0].logs;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM