Array.filter不能完全返回对象的属性吗?

亚历克斯·勒

我试图了解一些内置的数组方法。这是我的小功能代码,我想显示每个项目的“名称”和“类别”,这些项目存储在总价值大于1000的库存中。但是当我尝试打印bigPrice时,它始终显示的所有属性每个对象,我只想显示“名称”和“类别”。有人可以帮忙吗?

var products = [
{name: 'A', quantity: 2, unitPrice: 100, category: 'Electronic goods'},
{name: 'B', quantity: 1, unitPrice: 400, category: 'Electronic goods'},
{name: 'C', quantity: 5, unitPrice: 15, category: 'Clothing goods'},
{name: 'D', quantity: 2, unitPrice: 95, category: 'Clothing goods'},
{name: 'E', quantity: 300, unitPrice: 10, category: 'Home, Garden goods'},
{name: 'F', quantity: 60, unitPrice: 150, category: 'Handmade'},
{name: 'G', quantity: 10, unitPrice: 105, category: 'Automotive goods'}
];

var bigPrice = products.filter(function(item) {
if (item.quantity * item.unitPrice > 1000) {
    return item.name + ' || ' + item.category;
}
});

bigPrice;
Shubham Khatri

过滤器函数不返回自定义值,您需要一起使用map and filter或替代reduce

var products = [
{name: 'A', quantity: 2, unitPrice: 100, category: 'Electronic goods'},
{name: 'B', quantity: 1, unitPrice: 400, category: 'Electronic goods'},
{name: 'C', quantity: 5, unitPrice: 15, category: 'Clothing goods'},
{name: 'D', quantity: 2, unitPrice: 95, category: 'Clothing goods'},
{name: 'E', quantity: 300, unitPrice: 10, category: 'Home, Garden goods'},
{name: 'F', quantity: 60, unitPrice: 150, category: 'Handmade'},
{name: 'G', quantity: 10, unitPrice: 105, category: 'Automotive goods'}
];

var bigPrice = products.map(function(item) {
if (item.quantity * item.unitPrice > 1000) {
    return item.name + ' || ' + item.category;
}
}).filter(item => typeof item !== 'undefined');

console.log(bigPrice)

要么

var products = [
{name: 'A', quantity: 2, unitPrice: 100, category: 'Electronic goods'},
{name: 'B', quantity: 1, unitPrice: 400, category: 'Electronic goods'},
{name: 'C', quantity: 5, unitPrice: 15, category: 'Clothing goods'},
{name: 'D', quantity: 2, unitPrice: 95, category: 'Clothing goods'},
{name: 'E', quantity: 300, unitPrice: 10, category: 'Home, Garden goods'},
{name: 'F', quantity: 60, unitPrice: 150, category: 'Handmade'},
{name: 'G', quantity: 10, unitPrice: 105, category: 'Automotive goods'}
];

var bigPrice = products.filter(function(item) {
   return (item.quantity * item.unitPrice) > 1000
}).map(item => item.name + ' || ' + item.category);

console.log(bigPrice)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章