在我的JavaScript中,我有一个表示订购数量的整数,以及一个提供所有数量的对象:
{
"1": {
"quantity": 1,
"price": 10
},
"2": {
"quantity": 2,
"price": 20
},
"6": {
"quantity": 6,
"price": 50
},
"12": {
"quantity": 12,
"price": 80
}
}
我需要找到数量值大于我的订购数量但小于序列中下一个对象的数量值的对象。
例如,如果我的订购数量为8,则需要隔离:
"6": {
"quantity": 6,
"price": 50
},
所以我可以获得正确的价格。我尝试了各种LoDash方法,但似乎没有什么是正确的。有没有办法可以做到这一点?
您可以拿起键并反转数组,找到较小或相等的计数。
function find(object, quantity) {
return Object.keys(object).reverse().find(v => v <= quantity);
}
var object = { 1: { quantity: 1, price: 10 }, 2: { quantity: 2, price: 20 }, 6: { quantity: 6, price: 50 }, 12: { quantity: 12, price: 80 } };
console.log(find(object, 8));
根据您的描述,我假设您要尝试的是找到对应于高于输入数量的最小数量的记录。该示例实际上与该描述不匹配。如果要寻找相反的值(下一个最大的值,小于输入的值),可以翻转两个不等式。
some_prices = {
"1": {
"quantity": 1,
"price": 10
},
"2": {
"quantity": 2,
"price": 20
},
"6": {
"quantity": 6,
"price": 50
},
"12": {
"quantity": 12,
"price": 80
}
}
getNextQuantityPrice = (prices, quantity) => {
const largerQuantities = Object.values(prices)
.filter(value => value.quantity > quantity);
if (largerQuantities.length === 0) return null;
return largerQuantities
.reduce((min, next) => next.quantity < min.quantity ? next : min)
}
console.log(JSON.stringify(getNextQuantityPrice(some_prices, 2)));