Javascript Data Type How to - Loop through objects within an array, taking total of integer values








Question

We would like to know how to loop through objects within an array, taking total of integer values.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!-- ww w.  j av  a 2s .  c om-->
var basket = [
    {
        price: "25.00",
        id: "Hat"
    }, {
        price: "50.00",
        id: "Jacket"
    }
]
var total = basket.reduce( function( previousValue, currentValue ){ 
                                return previousValue += parseInt(currentValue.price) }, 0);

document.write(total)

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: