I am working on a Javascript array where I need to loop the 2nd array in the main array and get the total sum of a value of a particular field. below is what my JSON looks like. here I need to loop Array and get the sum of ps_lessons.lesson_length_minutes I need the O/P as 118 (20 + 22 + 33 + 43)
[
{
"sort_id": 1,
"category": "Introduction",
"ps_lessons": [
{
"id": "48ca672b-aaca-473c-b54b-3cf699da848b",
"sort_id": 1,
"lesson_title": "Welcome to the course",
"lesson_length_minutes": 20
},
{
"id": "3f0f5715-a442-4262-ad32-6fb653df62c2",
"sort_id": 2,
"lesson_title": "What is React JS?",
"lesson_length_minutes": 22
}
]
},
{
"sort_id": 2,
"category": "Fundamentals",
"ps_lessons": [
{
"id": "e28abd67-29a4-4bc9-a415-fb5db0aabfa9",
"sort_id": 4,
"lesson_title": "Fundamentals of React JS",
"lesson_length_minutes": 33
},
{
"id": "1d9668da-94e6-4085-bd89-176cc4e8e62d",
"sort_id": 3,
"lesson_title": "Fundamentals of JSX",
"lesson_length_minutes": 43
}
]
}
]
I tried something like the below by using the array method map 2 times but it's not working. can anyone suggest how to do this?
const extract_mins_and_sum = (result) => {
console.log('result', result);
result.map((single_row) =>
let sum = 0;
single_row.ps_lessons.map((single_row_lesson) =>
( console.log(single_row_lesson.lesson_length_minutes);
sum += single_row_lesson.lesson_length_minutes)
)
);
};
Thanks Venk