从AJAX响应中获取值

时间:2016-01-21 14:26:03

标签: javascript

我得到这样的回复

[
  {
    "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的新手

3 个答案:

答案 0 :(得分:2)

当您使用JSON的字符串表示时。要将其转换为JSON对象,可以使用JSON.parse()

要从数组中的每个对象获取id字段,您可以在ES6中使用Array#map显示Arrow function

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
&#13;
&#13;
&#13;

可以使用ES5中的匿名函数编写相同的代码。

JSON.parse(response).map(function (obj) {
    return {
        id: obj.id,
        name: obj.name
    };
});

&#13;
&#13;
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 = '<pre>' + JSON.stringify(ids, 0, 4) + '</pre>'; // For DEMO purpose
&#13;
&#13;
&#13;

答案 1 :(得分:1)

假设您在数据变量上获得此json

decorator

您可以轻松地将ID作为第一个元素的 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 } ] 来访问。 data[0].id将为您提供对象总数,以便您可以迭代

答案 2 :(得分:0)

您可以使用JSON.parse()将字符串转换为“等效”JavaScript对象。更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

在你的情况下,你可以这样做:

var obj = JSON.parse(response);         // an array in your case
var ids = obj.map(e => e.id);
var names = obj.map(e => e.name);

.map()次呼叫正在使用新的“胖箭头”运算符。这种近乎等效的语法可能更为熟悉:

var ids = obj.map( function(e) { return e.id; } );

阵列地图功能的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

[胖]箭头功能的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions