1

I'm trying to Sum Array amount of Laravel Relationship Using Vuejs using computed.

enter image description here

By the Way its Return NaN Result....

   computed: {
        subTotal() {
            return this.items.reduce((total, item) => {
                return total + parseFloat(item.deposits.amount);
            }, 0);
        }
    },

Thanks.....

3
  • 1
    You are using deposits.amount directly which is actually an array hence you cannot use reduce directly on array item but you should do that on item.deposits by iterating through items object. Commented Dec 20, 2019 at 10:07
  • 1
    Is it correct that your code should loop the items variable (which can't be seen in the image? It looks like what you really want is to loop the deposits. Because from this code, you're trying to get item.deposits.amount, but deposits is an array.. Commented Dec 20, 2019 at 10:08
  • @Jesper yep, as u say, but i dont know how to implement that? Can u give me any hint? Commented Dec 20, 2019 at 10:10

2 Answers 2

1

The below code will return an array of sum for all items within the array index wise.

computed: {
    subTotal() {
        let itemsum = []
        this.items.forEach(item => {
            if (item.deposits && item.deposits.length > 0) {
                let total_deposit = item.deposits.reduce((total, val) => {
                    return  parseFloat(total.amount) + parseFloat(val.amount);
                }, 0);
                itemsum.push(total_deposit);
            } else {
                itemsum.push(0);
            }                  
        })
        return itemsum
    }
},
Sign up to request clarification or add additional context in comments.

2 Comments

As i told it will return you array for sum of all deposits item wise as items is an array and you want sum of only deposits values. Please mention what output you are expecting properly.
i want sum of all amount in array deposits
0
  1. Do sum relationship in Laravel

    protected $appends = ['deposit_amount'];

    public function getDepositAmountAttribute(){ return $this->deposits()->sum('amount'); }

  2. VueJS Computed Property

    computed: { deposit_amount() { var amount = 0; for(let i = 0; i < this.item.deposits.length; i++) { amount += parseFloat(this.item.deposits[i].amount); } return amount; } }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.