3 回答

TA貢獻1895條經驗 獲得超7個贊
“......我想要特定類型值的所有最大值和最小值,而不是絕對最大值和絕對最小值。有什么辦法可以包括這個嗎?”
可能最自然/最明顯的方法是首先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",
"max" : 52.346377,
"min" : 0.1354055,
"date": "17-01-01",
"time": "21:38:17"
}, {
"type" : "b",
"max" : 55.3467377,
"min" : 0.1154055,
"date": "17-01-01",
"time": "22:38:17"
}, {
"type" : "b",
"max" : 48.3467377,
"min" : -0.1354055,
"date": "17-01-01",
"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; }

TA貢獻1820條經驗 獲得超9個贊
在 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,
"date": "17-01-01",
"time": "22:38:17"
},
{
"type" : "b",
"max" : 48.3467377,
"min" : -0.1354055,
"date": "17-01-01",
"time": "23:38:17"
}
]
}
console.log(filterArray(data2,'b'));
console.log(filterArray(data2,'a'));
console.log(filterArray(data2,'any'));

TA貢獻1859條經驗 獲得超6個贊
例如,您可以使用一個簡單的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);
現在讓我們注意這將在第一次出現正確的“類型”時停止(如果您有多個相同類型的條目);
如果你想考慮相同“類型”的多個條目,你可以結合 afilter和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
}] */
添加回答
舉報