Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Sum of nested object values in Array using JavaScript
When working with complex nested data structures in JavaScript, you often need to sum values from deeply nested objects within arrays. This guide demonstrates various approaches to calculate the sum of nested object values efficiently.
Understanding the Data Structure
Consider a JSON object with nested arrays and objects where we need to sum the costNum values:
let json = {
storeData: [
{
items: [
{
itemID: 12,
cost: {
costNum: 100,
},
},
{
itemID: 22,
cost: {
costNum: 250,
},
},
{
itemID: 19,
cost: {
costNum: 350,
},
},
],
},
],
};
Using forEach with Nested Loops
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sum Nested Object Values</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 20px;
}
.result {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
margin: 10px 0;
}
button {
padding: 10px 20px;
background: #007bff;
color: white;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Sum of Nested Object Values in Array</h1>
<div class="result"></div>
<button class="btn">Calculate Sum</button>
<p>Click the button to sum the nested costNum values from the JSON array</p>
<script>
let json = {
storeData: [
{
items: [
{
itemID: 12,
cost: {
costNum: 100,
},
},
{
itemID: 22,
cost: {
costNum: 250,
},
},
{
itemID: 19,
cost: {
costNum: 350,
},
},
],
},
],
};
let resEle = document.querySelector(".result");
document.querySelector(".btn").addEventListener("click", () => {
let sum = 0;
json.storeData.forEach((store) => {
store.items.forEach((item) => {
sum += item.cost.costNum;
});
});
resEle.innerHTML = "Total CostNum = " + sum;
});
</script>
</body>
</html>
Using reduce() Method
A more functional approach using the reduce() method for cleaner code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sum with Reduce</title>
</head>
<body>
<div id="output"></div>
<script>
let json = {
storeData: [
{
items: [
{ itemID: 12, cost: { costNum: 100 } },
{ itemID: 22, cost: { costNum: 250 } },
{ itemID: 19, cost: { costNum: 350 } }
]
}
]
};
// Using reduce for functional approach
let totalSum = json.storeData.reduce((storeSum, store) => {
return storeSum + store.items.reduce((itemSum, item) => {
return itemSum + item.cost.costNum;
}, 0);
}, 0);
document.getElementById("output").innerHTML = "Total using reduce: " + totalSum;
</script>
</body>
</html>
Output
Total CostNum = 700
Using flatMap() for Complex Structures
For more complex nested structures, flatMap() provides an elegant solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>FlatMap Example</title>
</head>
<body>
<div id="flatmap-result"></div>
<script>
let json = {
storeData: [
{
items: [
{ itemID: 12, cost: { costNum: 100 } },
{ itemID: 22, cost: { costNum: 250 } },
{ itemID: 19, cost: { costNum: 350 } }
]
}
]
};
// Using flatMap to flatten and sum
let sum = json.storeData
.flatMap(store => store.items)
.reduce((total, item) => total + item.cost.costNum, 0);
document.getElementById("flatmap-result").innerHTML = "Total using flatMap: " + sum;
</script>
</body>
</html>
Comparison of Methods
| Method | Readability | Performance | Use Case |
|---|---|---|---|
| forEach | Good | Fast | Simple nested loops |
| reduce | Very Good | Good | Functional programming style |
| flatMap + reduce | Excellent | Good | Complex nested structures |
Conclusion
Choose forEach for simple cases, reduce for functional style, and flatMap for complex nested structures. All methods effectively sum nested object values in JavaScript arrays.
Advertisements
