Getting values out of AJAX response
This question already has an answer here:
As you've the string representation of JSON. To convert it to JSON object, you can use JSON.parse()
.
To get the id
field from each of the object in the array, you can use Array#map
here shown using Arrow function in ES6.
JSON.parse(response).map(e => ({
id: e.id,
name: e.name
}));
var response = '[ { "id": "958315db-ca46-4b32-ad89-f0564a2bfa37", "name": "XXXX", "device_count": 3, "gateway_count": 2, "longitude": -109.207929275995, "latitude": 33.1906871835467 }, { "id": "4485e5ee-ba30-4103-8f24-c710efed3929", "name": "YYYY", "device_count": 0, "gateway_count": 0, "longitude": null, "latitude": null } ]';
var ids = JSON.parse(response).map(e => ({
id: e.id,
name: e.name
}));
console.log(ids);
document.body.innerHTML = '<pre>' + JSON.stringify(ids, 0, 4) + '</pre>'; // For DEMO purpose
Suppose you are getting this json on data variable
var data = [ { "id": "958315db-ca46-4b32-ad89-f0564a2bfa37", "name": "XXXX", "device_count": 3, "gateway_count": 2, "longitude": -109.207929275995, "latitude": 33.1906871835467 }, { "id": "4485e5ee-ba30-4103-8f24-c710efed3929", "name": "YYYY", "device_count": 0, "gateway_count": 0, "longitude": null, "latitude": null } ]
You can easily access the id as data[0].id
of first element. data.length
will give you the total number of objects so that you can iterate
You can use JSON.parse()
to turn the string into a "equivalent" JavaScript object. More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
In your case, you could do something like this:
var obj = JSON.parse(response); // an array in your case
var ids = obj.map(e => e.id);
var names = obj.map(e => e.name);
The .map()
calls are using the new "fat arrow" operator. This nearly-equivalent syntax may be more familiar:
var ids = obj.map( function(e) { return e.id; } );
Info on the Array map function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Info on [Fat] Arrow Functions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
链接地址: http://www.djcxy.com/p/31714.html上一篇: 将JSON字符串转换为JavaScript对象以进行迭代
下一篇: 从AJAX响应中获取值