为了清楚起见,给出一个对象数组,可能具有同质的键:
const data = [
{ name: "tomato", isHealthy: true, "calories": 300 },
{ name: "french fries", isHealthy: false, "calories": 1000 },
{ name: "lettuce", isHealthy: true, "calories": 100 },
{ name: "nacho cheese", isHealthy: false, "calories": 1200 },
{ name: "boring chicken", isHealthy: true, "calories": 500 },
];
一些过滤器会说:
const isHealthy = function(items) {
return items.filter(i => i.isHealthy);
};
const caloriesAbove = function(items, calories) {
return items.filter(i => i.calories > calories);
};
我希望能够像这样调用筛选器链:
wrapper(data).isHealthy().caloriesAbove(500).value.map(...)
很难理解lodash是如何做到这一点的。此外,有没有一种方法可以做到这一点,而不需要显式地展开才能获得值?这不是一个要求,因为我认为这可能不得不使用不受欢迎的黑客。
发布于 2018-08-21 03:56:28
我读了答案,我喜欢@Jonas做这件事的方式。我不知道你可以像这样简单地扩展数组。定义得到我的赞成票了!
话虽如此,我想知道当您只需创建一个filter函数来处理多个值并将其传递给数组的filter时,这种方法会有多大用处:
const data = [
{ name: "tomato", isHealthy: true, "calories": 300 },
{ name: "french fries", isHealthy: false, "calories": 1000 },
{ name: "lettuce", isHealthy: true, "calories": 100 },
{ name: "nacho cheese", isHealthy: false, "calories": 1200 },
{ name: "boring chicken", isHealthy: true, "calories": 500 },
];
const myFilterFn = ({isHealthy, calories}) => isHealthy && calories > 200
data.filter(myFilterFn).map(x => console.log(x))
我在更一般的视图中看到了这一点的价值,但对于过滤来说,它似乎有点过头了。
就我的两分钱。
https://stackoverflow.com/questions/51933281
复制相似问题