Getting values out of AJAX response
本问题已经有最佳答案,请猛点这里访问。
我得到这样的答复
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | [ { "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 } ] |
我如何用JavaScript解析它,并在一个数组中获取两个ID和名称?抱歉,我刚接触到javascript
因为您有JSON的字符串表示。要将其转换为JSON对象,可以使用
要从数组中的每个对象中获取
1 2 3 4 | JSON.parse(response).map(e => ({ id: e.id, name: e.name })); |
1 2 3 4 5 6 7 8 9 | 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 = '[cc lang="javascript"]' + JSON.stringify(ids, 0, 4) + ' |
';//用于演示目的>
同样的代码可以使用ES5中的匿名函数编写。
1 2 3 4 5 6 | JSON.parse(response).map(function (obj) { return { id: obj.id, name: obj.name }; }); |
1 2 3 4 5 6 7 8 9 10 | 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(function (obj) { return { id: obj.id, name: obj.name }; }); console.log(ids); document.body.innerHTML = '[cc lang="javascript"]' + JSON.stringify(ids, 0, 4) + ' |
';//用于演示目的>pre>
假设您正在获取数据变量上的JSON
1 | 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 } ] |
您可以很容易地以第一个元素的
可以使用
在您的案例中,您可以这样做:
1 2 3 | var obj = JSON.parse(response); // an array in your case var ids = obj.map(e => e.id); var names = obj.map(e => e.name); |
1 | var ids = obj.map( function(e) { return e.id; } ); |
关于array map函数的信息:https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/map
关于[fat]箭头函数的信息:https://developer.mozilla.org/en-us/docs/web/javascript/reference/functions/arrow_functions