我必须获取以下响应的值。
var response = { "data": [
{
"value": "Network problem",
"text": "Network problem",
"areas": [
{
"value": "Congestion",
"text": "Congestion",
"sub_areas": [
{
"value": "Congestion_1",
"text": "Congestion_1",
"id":"1"
},
{
"value": "Call D",
"text": "Call D",
"id":"2"
}]
},
{
"value": "Drop",
"text": "Drop",
"sub_areas": [
{
"value": "Drop_1",
"text": "Drop_1",
"id":"3"
}]
}
]};如果我有值"Network problem",那么我必须检索它的区域(ex: areas = ["Congestion","Drop"])。然后,我必须使用面积值重新获得子区域。如果面积值为"congestion",则为sub_areas =["congestion_1", "Call D"])。我该怎么做呢?
发布于 2016-07-07 18:28:53
根据Venky的建议,使用下划线这样的库可能是最好的方法。
如果您对原生JS解决方案感兴趣,我将在下面提供一个。
因为您的结构没有很多级别的叠置,所以可以考虑使用简单的方法,例如:
var node, root = {};
response.data.forEach(function(data) {
node = root[data.value] = {};
data.areas.forEach(function(area) {
node[area.value] = [];
area.sub_areas.forEach(function(subArea) {
node[area.value].push(subArea.value);
});
});
});示例输出#1:'data‘值的列表:
console.log(Object.keys(root));
["Network problem"]示例输出#2:“网络问题”的区域列表:
console.log(Object.keys(root['Network problem']));
["Congestion", "Drop"]示例输出#3:“网络问题”/“拥塞”的分区列表:
console.log(root['Network problem']['Congestion']);
["Congestion_1", "Call D"]请注意,根节点及其直接子节点是对象,而叶节点是数组。因此,最后一个示例使用了不同的语法。
附录
下面是我使用的响应对象,具有固定的格式。
var response = {
"data": [
{
"value": "Network problem",
"text": "Network problem",
"areas": [
{
"value": "Congestion",
"text": "Congestion",
"sub_areas": [
{
"value": "Congestion_1",
"text": "Congestion_1",
"id":"1"
},
{
"value": "Call D",
"text": "Call D",
"id":"2"
}
]
},
{
"value": "Drop",
"text": "Drop",
"sub_areas": [
{
"value": "Drop_1",
"text": "Drop_1",
"id":"3"
}
]
}
]
}
]
};https://stackoverflow.com/questions/38241901
复制相似问题