I have an object where Citems is an array of Object. Each object has status on or of and time.
JavaScript
x
16
16
1
{
2
Chapter: [
3
{
4
Cname: 'chapter 1',
5
Citems: [{status: 'on', time: 30},{status: 'on', time: 60}],
6
7
},
8
{
9
Cname: 'chapter 2',
10
Citems: [{status: 'on', time: 30},{status: 'off', time: 60}]
11
}
12
],
13
name: 'Something',
14
description: 'jfdgljfgdfjgldfkjglfd'
15
}
16
I want to generate an array or object from it that show total time for each status like below
JavaScript
1
5
1
{
2
on: 120,
3
off: 60
4
}
5
I tried with map and reduce but getting confused.
Advertisement
Answer
You just need a nested ‘sum’, here implemented using reduce()
and making use of computed properties to update the accumulator using the status
as key.
JavaScript
1
10
10
1
const data = { Chapter: [{ Cname: 'chapter 1', Citems: [{ status: 'on', time: 30 }, { status: 'on', time: 60 }], }, { Cname: 'chapter 2', Citems: [{ status: 'on', time: 30 }, { status: 'off', time: 60 }] }], name: 'Something', description: 'jfdgljfgdfjgldfkjglfd' };
2
3
const result = data.Chapter.reduce((a, { Citems }) => {
4
for (const { status, time } of Citems) {
5
a[status] += time;
6
}
7
return a;
8
}, { on: 0, off: 0 });
9
10
console.log(result);
Or using a for...of
loop
JavaScript
1
11
11
1
const data = { Chapter: [{ Cname: 'chapter 1', Citems: [{ status: 'on', time: 30 }, { status: 'on', time: 60 }], }, { Cname: 'chapter 2', Citems: [{ status: 'on', time: 30 }, { status: 'off', time: 60 }] }], name: 'Something', description: 'jfdgljfgdfjgldfkjglfd' }
2
3
const result = { on: 0, off: 0 };
4
5
for (const { Citems } of data.Chapter) {
6
for (const { status, time } of Citems) {
7
result[status] += time;
8
}
9
}
10
11
console.log(result);
To extend this to an array of such Chapter
objects you could nest it once more in a reduce()
.
JavaScript
1
25
25
1
const data = [
2
{
3
Chapter: [{ Cname: 'chapter 1', Citems: [{ status: 'on', time: 30 }, { status: 'on', time: 60 }], }, { Cname: 'chapter 2', Citems: [{ status: 'on', time: 30 }, { status: 'off', time: 60 }] }],
4
name: 'Something',
5
description: 'jfdgljfgdfjgldfkjglfd'
6
},
7
{
8
Chapter: [{ Cname: 'chapter 1', Citems: [{ status: 'on', time: 30 }, { status: 'off', time: 30 }], }, { Cname: 'chapter 2', Citems: [{ status: 'on', time: 30 }, { status: 'off', time: 60 }] }],
9
name: 'Something2',
10
description: 'asdfasdfasdfasdfasdfa'
11
}
12
]
13
14
const result = data.reduce((a, { name, Chapter }) => {
15
a[name] = Chapter.reduce((a, { Citems }) => {
16
for (const { status, time } of Citems) {
17
a[status] += time;
18
}
19
return a;
20
}, { on: 0, off: 0 });
21
22
return a;
23
}, {});
24
25
console.log(result);