得到了一个对象数组,需要按2个条件对其进行过滤。这些标准之一是向上计数的索引。
let data =
[{"hour": 1, "dayIndex": 0, "value": "something"},
{"hour": 1, "dayIndex": 1, "value": "something"},
{"hour": 1, "dayIndex": 3, "value": "something"},
{"hour": 2, "dayIndex": 0, "value": "something"},
{"hour": 2, "dayIndex": 1, "value": "something"},
// and so on
]
我需要一个由“小时”和“ dayIndex”过滤的对象数组,对于缺少的dayIndexes,创建一个空对象很重要。因此,对于hour = 1,我将需要以下内容:
let hourOneArray =
[
{"hour" : 1, "dayIndex": 0, "value": "something"},
{"hour" : 1, "dayIndex": 1, "value": "something"},
{}, //empty because dayIndex 2 is missing
{"hour" : 1, "dayIndex": 3, "value": "something"},
{}, //empty because dayIndex 4 is missing
]
我的方法是:
for(let i = 0; i < 4; ++i){
hourOneArray = data.filter((arg) => {
return ((arg.hour === 1) && (arg.dayIndex === i));
})
}
提前致谢
最佳答案
这是一个快速干净的解决方案,可以按小时过滤所有内容,以填补空白。利用地图并减少:D
let data =
[{"hour": 1, "dayIndex": 0, "value": "something"},
{"hour": 1, "dayIndex": 1, "value": "something"},
{"hour": 1, "dayIndex": 3, "value": "something"},
{"hour": 2, "dayIndex": 0, "value": "something"},
{"hour": 2, "dayIndex": 1, "value": "something"},
// and so on
]
let defaultArr = [];
data.forEach(val => defaultArr.push({}));
let output = data.reduce((hash, val) => {
let hour = val.hour;
let dayIndex = val.dayIndex;
if(!hash[hour]) hash[hour] = defaultArr.map(val => val);
hash[hour][dayIndex] = val;
return hash;
}, {})
console.log(output);
关于javascript - JavaScript array.filter()和迭代器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50596575/