我的PHP返回以下JSON(显示了2个条目,它可能更多,但结构将是相同的):
{
"0": {
"campaign_id": "31",
"title": "new title",
"description": "new description",
"destinations": {}
},
"1": {
"campaign_id": "32",
"title": "title",
"description": "description",
"destinations": {}
}
}
我想访问destinations
,其中campaign_id
与给定值匹配。我该怎么做?
答案 0 :(得分:2)
您可以使用Object.keys
和filter
执行匹配:
var obj = {...}; //your data object
var destinations = Object.keys(obj).filter(function(key) {
return obj[key].campaign_id === "32"
}).map(function(key) {
return obj[key].destinations;
});
答案 1 :(得分:2)
lodash.find
:var data = ...
var destinations = _.find(data, e => e.campaign_id == 31).destinations;
function find(data, predicate, def) {
for (var key in data) {
if (data.hasOwnProperty(key) && predicate(data[key], key)) {
return data[key];
}
}
return def;
}
var data = ...
var destinations = find(data, e => e.campaign_id== 31).destinations;
在这种情况下,如果服务器实际发送一个对象,其中项目本身由他们的campaign_id
键入,那么它将是最好的,那么它将只是:
var data = ...
data[31].destinations
答案 2 :(得分:1)
将您的回复转换为对象:
var obj = JSON.parse(response);
现在你可以遍历JSON:
var destinations;
for (var key in obj) {
if (obj[key].campaign_id == "value") {
destinations = obj[key].destinations;
break;
}
}
console.log(destinations);