我有一个包含产品详细信息的对象,包括类别、颜色、使用技巧和价格。 现在,我想通过提供我对象的最低价格和最高价格来找到所有对象:
const products = [{
name: 'Product 1',
usage: 'Home',
skill: 'Easy',
color: 'blue',
price: 100.00
}, {
name: 'Product 2',
usage: 'Home',
skill: 'Intermediate',
color: 'red',
price: 120.00
}, {
name: 'Product 3',
usage: 'Office',
skill: 'Intermediate',
color: 'green',
price: 190.00
}, {
name: 'Product 4',
usage: 'Office',
skill: 'Advanced',
color: 'blue',
price: 260.00
}, {
name: 'Product 5',
usage: 'Warehouse',
skill: 'Advanced',
color: 'white',
price: 320.00
}, {
name: 'Product 6',
usage: 'Farm',
skill: 'Intermediate',
color: 'red',
price: 120.00
}, {
name: 'Product 7',
usage: 'Space',
skill: 'Advanced',
color: 'green',
price: 150.00
}, {
name: 'Product 8',
usage: 'Bathroom',
skill: 'Easy',
color: 'black',
price: 9.00
}];
假设我提供了 minPrice = 100 和 maxPrice = 190 所以它应该返回我:
[{
name: 'Product 1',
usage: 'Home',
skill: 'Easy',
color: 'blue',
price: 100.00
}, {
name: 'Product 2',
usage: 'Home',
skill: 'Intermediate',
color: 'red',
price: 120.00
}, {
name: 'Product 3',
usage: 'Office',
skill: 'Intermediate',
color: 'green',
price: 190.00
}, {
name: 'Product 6',
usage: 'Farm',
skill: 'Intermediate',
color: 'red',
price: 120.00
}, {
name: 'Product 7',
usage: 'Space',
skill: 'Advanced',
color: 'green',
price: 150.00
}]
是否有任何预定义的 lodash 函数来获取此信息?
最佳答案
对于lodash,你可以使用_.fliter()像那样:
_.filter(products, function(p) {
return p.price >= 100 && p.price <= 190;
});
它将返回一个包含所有匹配项的新数组。根据the below example ,你可以将它存储在一个变量中,并用它做任何你想做的事。
您还可以将 _.filter()
包装在一个函数中:
function filterProduct(minPrice, maxPrice) {
return _.filter(products, function(p) {
return p.price >= minPrice && p.price <= maxPrice;
});
}
Jsfiddle 你的例子在这里:https://jsfiddle.net/maximelafarie/kps08L5x/4/
关于javascript - lodash - 通过提供两个要在其中查找的值来查找所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49939222/