我有一个产品索引列表,每个产品都有一个价格以及一系列的散装价格。我想过滤掉所有高于产品基本价格的批量价格。使用诸如解构之类的ES6功能的最佳方法是什么。
这是价格表:
prices: {
foo: {
price: 160,
bulkPricing: [
{price: 150, minimumQuantity: 10},
{price: 140, minimumQuantity: 20},
{price: 130, minimumQuantity: 30}
]
},
bar: {
price: 160,
bulkPricing: [
{price: 180, minimumQuantity: 10},
{price: 140, minimumQuantity: 20},
{price: 130, minimumQuantity: 30}
]
}
}
您会看到第二个产品的第一个批量价格高于基本价格,因此应将其删除。所以结果应该是:
prices: {
foo: {
price: 160,
bulkPricing: [
{price: 150, minimumQuantity: 10},
{price: 140, minimumQuantity: 20},
{price: 130, minimumQuantity: 30}
]
},
bar: {
price: 160,
bulkPricing: [
{price: 140, minimumQuantity: 20},
{price: 130, minimumQuantity: 30}
]
}
}
我可以这样:
Object.entries(prices).map(([sku, product])=> {
return {
[sku]: {
...product,
bulkPricing: product.bulkPricing.filter(bp => bp.price < product.price)
}
}
}
)
但这当然会返回一个数组:
[ { foo: { price: 160, bulkPricing: [{price: 150, minimumQuantity: 10},
{price: 140, minimumQuantity: 20},
{price: 130, minimumQuantity: 30}] } },
{ bar: { price: 160, bulkPricing: [{price: 140, minimumQuantity: 20},
{price: 130, minimumQuantity: 30}] } } ]
所以我想我的问题是,使用最新的ES6技术,如何根据对象中的数组过滤对象中的对象,然后返回修改后的对象?
答案 0 :(得分:1)
只需将forEach
与函数filter
一起使用,即可仅获得price
等于或小于特定price
的那些对象。
let obj = { prices: { foo: { price: 160, bulkPricing: [{ price: 150, minimumQuantity: 10 }, { price: 140, minimumQuantity: 20 }, { price: 130, minimumQuantity: 30 } ] }, bar: { price: 160, bulkPricing: [{ price: 180, minimumQuantity: 10 }, { price: 140, minimumQuantity: 20 }, { price: 130, minimumQuantity: 30 } ] } }};
Object.values(obj.prices).forEach(p => p.bulkPricing = p.bulkPricing.filter(b => b.price <= p.price));
console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
ES6和解构
Object.keys(prices).reduce((obj, key) => ({
...obj,
[key]: {
...prices[key],
bulkPricing: prices[key].bulkPricing
.filter(({ price }) => price <= prices[key].price)
}
}), {});
注意 :它不使用Object.values
,因为它在较旧的浏览器中尚未得到广泛支持,并且不会更改price对象。 / em>
答案 2 :(得分:0)
您需要做的就是filter
bulkPricing
数组,首先创建一个副本以避免原始对象的变异:
const prices = {
001: {
price: 160,
bulkPricing: [
{price: 150, minimumQuantity: 10},
{price: 140, minimumQuantity: 20},
{price: 130, minimumQuantity: 30}
]
},
002: {
price: 160,
bulkPricing: [
{price: 180, minimumQuantity: 10},
{price: 140, minimumQuantity: 20},
{price: 130, minimumQuantity: 30}
]
}
};
const newPrices = JSON.parse(JSON.stringify(prices));
Object.values(newPrices).forEach((item) => {
const { price: basePrice, bulkPricing } = item;
item.bulkPricing = item.bulkPricing.filter(({ price }) => price < basePrice);
});
console.log(newPrices);