There is an array of price objects. Each price object has its value and application condition, which depends on the quantity of products ordered for this price.
For example, in the basket there is a Pan product in the amount of 125 pieces for the price of 2 per piece. I'm trying to get and display the next possible price for this product (if you look below, this is 1 per piece, if more than 500 pieces of goods are ordered).
// В корзине лежит товар Pan в количестве 125 штук по цене 2 за штуку. let cart = [{ id: 5854, name: 'Pan', quantity: 125, price: 2, attributes: { // Все возможные цены на товар Pan в зависимости от заказанного количества prices: [{ id: 1, value: 10, condition_quantity: 0, }, { id: 2, value: 8, condition_quantity: 5, }, { id: 3, value: 6, condition_quantity: 10, }, { id: 4, value: 4, condition_quantity: 50, }, { id: 777, value: 1, condition_quantity: 500, }, { id: 900, value: 2, condition_quantity: 100, }, ] }, }]; function conditionPrice(item) { //все цены, кроме текущей let prices = item.attributes.prices.filter(row => row.value != item.price); //перебираем и сохраняем только те, которые имеют условие для применения цены let prices_for_select = []; for (let key in prices) { let price = prices[key]; if (price.condition_quantity > 0) { prices_for_select.push(price); } } //определяем, какая цена подходит if (prices_for_select.length > 0) { let min = prices_for_select[0]; for (let key in prices_for_select) { let price = prices_for_select[key]; if (price.condition_quantity < min.condition_quantity && price.condition_quantity > item.quantity) { min = price; } } return min; } return false; } console.log(conditionPrice(cart[0])); But something is wrong ...
Expected output
Example 1
- Ordered goods 125.
- Next price - 1 from 500 pieces
Example 2
- Ordered goods 505.
- Next price - no
Example 3
- Ordered goods 2.
- Next price - 8 from 5 pieces
Where am I wrong?