【发布时间】:2023-02-24 11:38:18
【问题描述】:
背景
我有以下数据集
let animals =
[
{id:1, attributes:[{ title:'cat',score:3, weight:30 }]},
{id:2, attributes:[{ title:'cat',score:4, weight:22 }]},
{id:3, attributes:[{ title:'dog',score:5, weight:26 }]}
{id:4, attributes:[{ title:'dog',score:5, weight:22 }]}
]
我的要求是让它看起来像这样:
let animals =
[
{ animal:'cat',avg_score:3.5, avg_weight:26 },
{ animal:'dog',avg_score:5, avg_weight:24 }
]
其中 avg_score 和 avg_weight 应该是相应标题的得分和权重的平均值。
阅读 loadash 的文档,我能够弄清楚,
- 我们需要使用 _.groupBy() 函数来按标题分组
- 我们需要使用_mean()函数来取平均值
我无法弄清楚如何一起完成这项工作。到目前为止我尝试了什么-
const answer = _( animals ) .groupBy( 'attributes.title' ) .map( () => ( { title: attributes.title, score: _.mean(attribute.score), weight: _.mean(attribute.weight), } ) ) .value(); console.log( "Master Data : " + answer );但是,由于标题、分数和权重是子项,我们需要某种循环来迭代并获取相应行的实体,因此我无法进一步处理。例如,赋值应该类似于
'title' : row.attributes.title,其中行是来自循环的迭代的引用。 有人可以帮忙展开这个吗?
【问题讨论】:
标签: javascript reactjs