Search code examples
javascriptoopobjectfindfor-in-loop

Push to array inside a for in Javascript


I have an object, this.items, that I am running a for in on, then using the find method to get all the products by id. I'm attempting to set a salesTax amount based on a conditional (if taxPercent > 0), but the loop is going through more than the expected amount of times and thus the taxPercent is larger than required.

total() {
    let total = 0
    let tax = []
    let importDuty = .05

    for (let productId in this.items) {
        total += this.inventory.products.find(product => {
            if (product.taxPercent > 0) {
                tax.push(product.price * product.taxPercent)
            }
            return product.id == productId
        }).price * this.items[productId]
    }

    tax = tax.reduce((a, b) => a + b, 0)

    let importDutyToApply = total * importDuty
    total = total + importDutyToApply + tax

    let response = {
        'total': total,
        'tax': tax
    }

    return response
}

I'm wondering how I can set the total tax to apply for any items that do not have the taxPercent set to 0. So, if I had three items and one of them required a 10 percent tax on $100, the total should be $10. Likewise if I had many items with some requiring the 10 percent tax and others not, it would only add up for the ones that require it. Any thoughts?


Solution

  • The function you pass to find gets called a load of times. You just want to add tax for the product it found, not for everything it looked at on the way.

    const product = this.inventory.products.find( product => product.id == productId );
    if (product.taxPercent > 0) {
        tax.push(product.price * product.taxPercent)
    }
    total += product.price * this.items[productId]