问题描述
我有一个看起来像这样的数据结构:
var data2 = {
"name" : "history","list": [{
"type" : "a","max" : 52.346377,"min" : 0.1354055,"date": "17-01-01","time": "21:38:17"
},{
"type" : "b","max" : 55.3467377,"min" : 0.1154055,"time": "22:38:17"
},"max" : 48.3467377,"min" : -0.1354055,"time": "23:38:17"
}]
}
我希望能够迭代此数据的list
属性,并检查列表项的type
值是否与另一个提供的值匹配。如果是这样,我想收集max
和min
值。
一个人怎么能完成这项任务?我不知道该怎么解决。
谢谢。
解决方法
在data.list上使用过滤器将仅提供那些类型与搜索值相同的对象。然后使用map创建具有最小值/最大值的新对象。
function filterArray(array,value) {
let result = array.list.filter( obj => obj.type===value).map( filtered => {
return {max: filtered.max,min: filtered.min}
});
return result;
}
var data2 = {
"name" : "history","list": [
{
"type" : "a","max" : 52.346377,"min" : 0.1354055,"date": "17-01-01","time": "21:38:17"
},{
"type" : "b","max" : 55.3467377,"min" : 0.1154055,"time": "22:38:17"
},"max" : 48.3467377,"min" : -0.1354055,"time": "23:38:17"
}
]
}
console.log(filterArray(data2,'b'));
console.log(filterArray(data2,'a'));
console.log(filterArray(data2,'any'));
,
例如,您可以使用简单的for ... of
循环;
let checkType = "a";
let max,min;
for (let entry of data2.list) {
if (entry.type === checkType) {
max = entry.max;
min = entry.min;
break;
}
}
console.log(min,max);
现在我们要注意,这将在首次出现正确的“类型”时停止(如果您有多个具有相同类型的条目);
如果您要考虑同一“类型”的多个条目,则可以组合一个filter
和map
迭代,例如:
let checkType = "b";
let minMaxValues = data2.list
.filter(e => e.type === checkType)
.map(e => { min : e.min,max : e.max });
console.log(minMaxValues);
/*
[{
min : 0.1154055,max : 55.3467377
},{
min : -0.1354055,max : 48.3467377
}] */
,
“ ...我想要特定类型值的所有最大值和最小值,而不是绝对的最大值和绝对的最小值。有什么方法可以包含此值?”
最自然/最明显的方法是首先filter
提供的匹配type
中的任何列表项...
data2.list.filter(item => item.type === typeToCheckFor)
...,然后在第二步中map
过滤后的数组的任何项目...
.map(item => { min: item.min,max: item.max });
另一种方法是在一个迭代周期内reduce
进行结果...
var data2 = {
"name" : "history","list": [{
"type" : "a","time": "21:38:17"
},{
"type" : "b","time": "22:38:17"
},"time": "23:38:17"
}]
}
function collectMinMaxValuesOfMatchingType(collector,item) {
if (item.type === collector.type) {
collector.list.push({
//type: item.type,min: item.min,max: item.max
})
}
return collector;
}
console.log(
data2.list.reduce(collectMinMaxValuesOfMatchingType,{
type: 'b',list: []
}).list
);
console.log(
data2.list.reduce(collectMinMaxValuesOfMatchingType,{
type: 'a',list: []
}).list
);
console.log(
data2.list.reduce(collectMinMaxValuesOfMatchingType,{
type: 'foo',list: []
}).list
);
.as-console-wrapper { min-height: 100%!important; top: 0; }