如何在JavaScript中以lodash';包裹?
需要明确的是,给定一组对象(可能具有同质键):如何在JavaScript中以lodash';包裹?,javascript,lodash,ecmascript-2016,Javascript,Lodash,Ecmascript 2016,需要明确的是,给定一组对象(可能具有同质键): const data = [ { name: "tomato", isHealthy: true, "calories": 300 }, { name: "french fries", isHealthy: false, "calories": 1000 }, { name: "lettuce", isHealthy: true, "calories": 100 }, { name: "nacho cheese", isHealth
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().caroriesabove(500).value.map(…)
很难看出洛达斯是如何做到这一点的。此外,是否有一种方法可以做到这一点,而不必显式展开以获取值?这不是一个要求,因为我认为这可能需要使用不受欢迎的黑客。lodash就是这样做的:
function wrapper(items) {
return {
value: items,
isHealthy() {
return wrapper(items.filter(it => it.isHealthy));
},
caloriesAbove(calories) {
return wrapper(items.filter(it => it.calories > calories));
},
};
}
此外,是否有一种方法可以做到这一点,而不必显式展开以获取值
由于ES6,您可以扩展阵列:
class Items extends Array {
isHealthy() {
return this.filter(it => it.isHealthy);
}
}
要将现有数组转换为项目,只需执行Items。从(数组)
或新项目(…数组)
,您可以:
items
.filter(it => it.calories > 2) // native methods can be used, they return Item instances, not Arrays
.isHealthy() // our custom methods also work
.map(it => it.name)[0] //its a regular array with indices.
我读了答案,我喜欢@Jonas做这件事的方式。不知道你可以这样简单地扩展数组。Def。我投了一票 话虽如此,我想知道当您可以简单地创建一个filter函数来处理多个值并将其传递给数组的filter时,这种方法有多有用:
const数据=[
{名称:“番茄”,isHealthy:true,“卡路里”:300},
{名称:“炸薯条”,isHealthy:false,“卡路里”:1000},
{名称:“莴苣”,isHealthy:true,“卡路里”:100},
{名称:“纳乔奶酪”,isHealthy:false,“卡路里”:1200},
{name:“无聊鸡”,isHealthy:true,“卡路里”:500},
];
常量myFilterFn=({isHealthy,卡路里数})=>isHealthy&&Carries>200
data.filter(myFilterFn).map(x=>console.log(x))