gpt4 book ai didi

javascript减少数组中对象的多个键

转载 作者:行者123 更新时间:2023-11-30 11:15:40 24 4
gpt4 key购买 nike

我有以下类型的对象映射(下面的示例数据)

{[date:string]:Array<{[type:string]:{amount:number, price:number}}>}

我需要将数组缩减为一个包含金额总和和平均价格的对象

我已经阅读了几篇关于如何减少对象上的数据的文章,例如

How to map and reduce over an array of objects?

Javascript reduce on array of objects

在我的例子中,“类型”是 ["PV","BHKW","FALLBACK"] 的枚举,但它可以扩展。除了为 in 循环编写声明之外,我想不出如何使用 array.reduce 来更优雅地完成此任务。

有什么建议吗?

{
"2018-08-01T11:00:00+02:00": [
{
"BHKW": {
"amount": 131,
"price": 85
},
"FALLBACK": {
"amount": 84,
"price": 1
}
},
{
"BHKW": {
"amount": 307,
"price": 58
},
"PV": {
"amount": 4,
"price": 60
}
}
],
"2018-08-01T12:00:00+02:00": [
{
"BHKW": {
"amount": 288,
"price": 59
},
"PV": {
"amount": 742,
"price": 73
}
},
{
"BHKW": {
"amount": 250,
"price": 49
},
"PV": {
"amount": 507,
"price": 98
}
},
{
"PV": {
"amount": 368,
"price": 22
},
"BHKW": {
"amount": 357,
"price": 73
}
},
{
"FALLBACK": {
"amount": 135,
"price": 62
},
"BHKW": {
"amount": 129,
"price": 93
}
}
],

最佳答案

您可以使用 lodash#mapValues转换对象 data 对象的每个值。要组合具有相同键值的所有对象,您可以使用 lodash#mergeWith使用回调测试是否将评估正在转换的键。

const result = _.mapValues(data, collection => 
_.mergeWith({}, ...collection, (a = 0, b = 0, key) =>
['amount', 'price'].includes(key)
? a + b
: void 0 // is equivalent to undefined to retain current value
));

const data = {
"2018-08-01T11:00:00+02:00": [
{
"BHKW": {
"amount": 131,
"price": 85
},
"FALLBACK": {
"amount": 84,
"price": 1
}
},
{
"BHKW": {
"amount": 307,
"price": 58
},
"PV": {
"amount": 4,
"price": 60
}
}
],
"2018-08-01T12:00:00+02:00": [
{
"BHKW": {
"amount": 288,
"price": 59
},
"PV": {
"amount": 742,
"price": 73
}
},
{
"BHKW": {
"amount": 250,
"price": 49
},
"PV": {
"amount": 507,
"price": 98
}
},
{
"PV": {
"amount": 368,
"price": 22
},
"BHKW": {
"amount": 357,
"price": 73
}
},
{
"FALLBACK": {
"amount": 135,
"price": 62
},
"BHKW": {
"amount": 129,
"price": 93
}
}
]
};

const result = _.mapValues(data, collection =>
_.mergeWith({}, ...collection, (a = 0, b = 0, key) =>
['amount', 'price'].includes(key)
? a + b
: void 0 // is equivalent to undefined to retain current value
));

console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

关于javascript减少数组中对象的多个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51690140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com