如何从嵌套对象中重新计算对象?



我有一个对象,其中Citems是object的数组。每个对象都有on或of和time的状态

{
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'
}

我想从中生成一个数组或对象,显示每个状态的总时间,如下所示

{
on: 120,
off: 60
}

我尝试了map和reduce,但是很困惑。

您只需要一个嵌套的'sum',这里使用reduce()实现,并使用计算属性来更新累加器,使用status作为键。

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' };
const result = data.Chapter.reduce((a, { Citems }) => {
for (const { status, time } of Citems) {
a[status] += time;
}
return a;
}, { on: 0, off: 0 });
console.log(result);

或者使用for...of循环

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' }
const result = { on: 0, off: 0 };
for (const { Citems } of data.Chapter) {
for (const { status, time } of Citems) {
result[status] += time;
}
}
console.log(result);

要将其扩展到这样的Chapter对象的数组,您可以将其再次嵌套在reduce()中。

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'
},
{
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 }] }],
name: 'Something2',
description: 'asdfasdfasdfasdfasdfa'
}
]
const result = data.reduce((a, { name, Chapter }) => {
a[name] = Chapter.reduce((a, { Citems }) => {
for (const { status, time } of Citems) {
a[status] += time;
}
return a;
}, { on: 0, off: 0 });
return a;
}, {});
console.log(result);

let obj = {Chapter: [{_id: '624568b157da1d351910c576',Cname:'chapter 1',Citems: [{status: 'on',time: 30},{status: 'on',time: 60}],},{_id:'456a5857da1d351910c577',Cname: 'chapter 2',Citems: [{status:'on',time: 30},{status: 'off',time: 60}]}],_id: '6245f975d17514e0eb9092f7',name:'Something',description:'fdgljfgdfjgldfkjglfd'}
console.log(function() {
let on=0, off=0; //define return variables (if there is not 'on' or 'off' element at the object, the amount is 0)
obj['Chapter'].forEach(function(elem) {
if (elem['Citems']) { //if the list item of 'Chapter' does not have a 'Citems' attribute, we will not deal with it
elem['Citems'].forEach(function(e) {
if (e['status'] == 'on') {on += e['time']} else if (e['status'] == 'off') {off += e['time']}
})
}
});
return {
on: on,
off: off
}
}())

最新更新