我有这种形式的数组:
[
{
username: '',
id: '',
moreInfo: {
infoDate: ''
}
}
]
我需要根据infoDate进行过滤,无论它是否在两个特定的日期之间。
我有一个接受对象的函数,该字段用于搜索范围并返回:
return resultDate >= fromDate && resultDate <= thruDate;
但是我该如何过滤这样的数组。 我尝试过
userData.filter(userData => functionthatFiltersDate(userData.moreInfo, {from,thru}, 'infoDate')
FiltersDate函数是一个接受对象作为输入并注明日期以检查范围的函数:
functionthatFiltersDate = (
result,
{ fromDate, thruDate },
fieldName
) => {
let resultDate = result[fieldName];
if (!isDate(resultDate)) {
resultDate = moment(result[fieldName]).toDate();
}
if (!isDate(fromDate)) {
fromDate = moment(fromDate).toDate();
}
if (!isDate(thruDate)) {
thruDate = moment(thruDate).toDate();
}
return resultDate >= fromDate && resultDate <= thruDate;
};
如何根据内部的另一个对象属性过滤对象数组? 任何帮助表示赞赏!
答案 0 :(得分:-1)
以这种方式调用函数:
function fooBar(item ){
// ....
// return truthy condition
};
var result = arr.filter(fooBar);
-
将参数传递给过滤器函数:
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
/**
* Array filters items based on search criteria (query)
*/
const filterItems = (query) => {
return fruits.filter((el) =>
el.toLowerCase().indexOf(query.toLowerCase()) > -1
);
}
console.log(filterItems('ap')); // ['apple', 'grapes']
console.log(filterItems('an')); // ['banana', 'mango', 'orange']
来源:Mozilla Docs
-
根据嵌套值过滤数组:
var arr = [
{foo: 'item1', nested: {nestedFoo: 'returnThis'} },
{foo: 'item2', nested: {nestedFoo: 'notThis'} },
];
var result = arr.filter(item => item.nested.nestedFoo == 'returnThis');
// result variable now contains an array with one object
console.log(result) // array
console.log(result[0]) // object
console.log(result[0].foo) // 'item1'
Refer to this question for explanation on how to access nested values
-
更清晰:
var arr = [
{
username: '',
id: '',
moreInfo: {
infoDate: ''
}
},
{
username: '',
id: '',
moreInfo: {
infoDate: ''
}
},
...
];
const filterItems = (fromDate, thruDate, fieldName) => {
return arr.filter((item) =>
item.moreInfo.infoDate >= fromDate && item.moreInfo.infoDate < thruDate
);
}