我有一个对象的avg[]
数组和avgphone, avgemail and avgemail
对象的属性。如何在一个函数中获取avgphone, avgemail and avgemail
值?可以,但是似乎效率不高,
AvgPhone = () => {
const nr = this.state.avg.map( (t, idx) => (
t.avgphone||0
))
return nr;
}
AvgEmail= () => {
const nr = this.state.avg.map( (t, idx) => (
t.avgemail||0
))
return nr;
}
AvgLiveChat= () => {
const nr = this.state.avg.map( (t, idx) => (
t.avglive||0
))
return nr;
}
最佳答案
通过一个forEach
循环,您可以将所有对象合并到一个对象中。
const avg = [{ avgphone: 2, avgemail: 1 }, { avglive: 5 }];
const res = {AvgPhone: [], AvgEmail: [], AvgLiveChat: []};
avg.forEach(t => {
res.AvgPhone.push(t.avgphone || 0);
res.AvgEmail.push(t.avgemail || 0);
res.AvgLiveChat.push(t.avglive || 0);
});
console.log(res);
关于javascript - 在一个函数React中获取数组对象的属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60566877/