给出以下JSON:
[
{
"group": "satellite-1",
"data": [
{
"label": "feed1-1_TargetA",
"data": [
{"timeRange": ["11:40:00 AM", "11:40:20 AM"], val: "TargetA"},
{"timeRange": ["11:40:20 AM", "11:40:40 AM"], val: "TargetA"},
{"timeRange": ["11:41:00 AM", "11:41:20 AM"], val: "TargetA"},
]
},
{
"label": "feed1-1_TargetB",
"data": [
{"timeRange": ["11:40:40 AM", "11:41:00 AM"], val: "TargetB"},
{"timeRange": ["11:41:00 AM", "11:41:20 AM"], val: "TargetB"}
]
},
{
"label": "feed1-1_TargetC",
"data": [
{"timeRange": ["11:40:40 AM", "11:41:00 AM"], val: "TargetC"},
{"timeRange": ["11:41:00 AM", "11:41:20 AM"], val: "TargetC"},
]
},
{
"label": "feed1-1_TargetD",
"data": [
{"timeRange": ["11:40:40 AM", "11:41:00 AM"], val: "TargetD"},
{"timeRange": ["11:41:00 AM", "11:41:20 AM"], val: "TargetD"},
]
},
{
"label": "feed1-2_TargetB",
"data": [
{"timeRange": ["11:40:20 AM", "11:40:40 AM"], val: "TargetB"}
]
}
]
},
{
"group": "satellite-2",
"data": [
{
"label": "feed2-1_TargetA",
"data": [
{"timeRange": ["11:40:20 AM", "11:40:40 AM"], val: "TargetA"},
{"timeRange": ["11:41:00 AM", "11:41:20 AM"], val: "TargetA"},
]
},
{
"label": "feed2-1_TargetB",
"data": [
{"timeRange": ["11:40:40 AM", "11:41:00 AM"], val: "TargetB"},
{"timeRange": ["11:41:00 AM", "11:41:20 AM"], val: "TargetB"}
]
},
{
"label": "feed2-1_TargetC",
"data": [
{"timeRange": ["11:40:40 AM", "11:41:00 AM"], val: "TargetC"},
{"timeRange": ["11:41:00 AM", "11:41:20 AM"], val: "TargetC"},
]
},
{
"label": "feed2-2_TargetB",
"data": [
{"timeRange": ["11:40:20 AM", "11:40:40 AM"], val: "TargetB"}
]
}
]
}
]
我试图比较哪些Feed看到了最多的目标。
到目前为止,我已经解决了这个问题,因为我可以循环访问JSON并通过比较每个Feed的长度来返回“最敏锐的Feed”。
/*
* Compare length of each sensor block in data to determine which sensor
* is most observant
*/
var getMostObservantFeeds = function(entry){
var bestFeed = null;
for(var d of entry.data){
if (bestFeed == null){
bestFeed = d;
}
if (bestFeed.data.length < d.data.length){
bestFeed = d;
}
}
bestFeed = bestFeed || {};
return bestFeed.label
])
};
var getMostObservantFeed = function(data_JSON){
return data_JSON.map(x => getMostObservantFeeds(x));
};
然而,对于饲料与另一种饲料长度相同的情况,我无法做到这一点。
如果2个Feed看到相同数量的目标(并且是看到的最高数量),我该如何返回最佳Feed的列表? (即satellite2:feed2-1_TargetA,feed2-1_TargetB,feed2-1_TargetC)
答案 0 :(得分:1)
如何记录最大值并与每次比较。也许只是将标签存储在一个数组中,因为这就是你要回来的所有内容吗?
var getMostObservantFeed = function(entry){
var bestLabels = [];
var max = 0;
for(var d of entry.data){
if (d.data.length >= max){
max = d.data.length;
bestLabels.push(d.label);
}
}
return bestLabels;
};
答案 1 :(得分:0)
我建议您使用第二个条件来检查bestFeed.data
和d.data
是否具有相同的长度。在for循环中的第二个if语句之后添加类似的东西:
else if(bestFeed.data.length === d.data.length){
//do further checking here
}
在这种情况下,您可以再次比较bestfeed
和d
(可能是timerange
属性)。
我还建议您使用d
以外的其他内容,例如i
或item