0

I am using nodejs. I get the json data with the code below.

I want to get the sum of "element.debt". How can I do that ?

so I want to get the sum of "element.debt" in json


            var sonuc = 0;
            result.forEach(element => {
                sonuc = element.debt
            });
            console.log(sonuc)

{
    "message": "customer debst",
    "result": [
        {
            "id": 3,
            "user_id": 15,
            "debt": "100.00",
            "received_amount": "150.00",
            "business_code": "123456",
            "debt_description": "description here"
        },
        {
            "id": 2,
            "user_id": 15,
            "debt": "110.00",
            "received_amount": "150.00",
            "business_code": "123456",
            "debt_description": "description here"
        }
    ]
}


5
  • sonuc += element.debt inside forEach Commented Jan 20, 2021 at 14:24
  • sonuc += parseFloat(element.debt, 10) inside forEach Commented Jan 20, 2021 at 14:25
  • very thanksssss :)) @kgangadhar Commented Jan 20, 2021 at 14:25
  • 2
    Does this answer your question? How to sum json array Commented Jan 20, 2021 at 14:27
  • Thanks guys, our friend @kgangadhar reply made it easy for me. Commented Jan 20, 2021 at 14:29

1 Answer 1

0

Here is a basic way to sum the debt using reducer and keeping the decimals

const reducer = (accumulator, currentValue) => (parseFloat(accumulator.debt) + parseFloat(currentValue.debt)).toFixed(2);

console.log(result.reduce(reducer));
Sign up to request clarification or add additional context in comments.

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.