[英]Lodash - Aggregate values in JSON object without specifying keys
I am trying to get a sum of values in a JSON array grouped by a shop_id
and key, and get the output in the same format.我试图在按shop_id
和键分组的 JSON 数组中获取值的总和,并以相同的格式获取 output。 I tried doing it on the DB since I am not familiar with Lodash at all but I reckon sending and receiving data from DB would not be as efficient.我尝试在 DB 上执行此操作,因为我根本不熟悉 Lodash,但我认为从 DB 发送和接收数据不会那么有效。
With an array like this:使用这样的数组:
[
{
sales: {"bicycle": 2, "skateboard": 5},
shop_id: 6321
},
{
sales: {"bicycle": 1, "skateboard": 3},
shop_id: 6243
},
{
sales: {"bicycle": 3, "skateboard": 4},
shop_id: 6243
}
]
The output should look like: output 应如下所示:
[
{
sales: {"bicycle": 2, "skateboard": 5},
shop_id: 6321
},
{
sales: {"bicycle": 4, "skateboard": 7},
shop_id: 6243
}
]
How can I achieve this with Lodash?如何使用 Lodash 实现这一目标? Or are there better ways to handle it without it?或者有没有更好的方法来处理它?
This should work:这应该有效:
What it does is:它的作用是:
const input = [ { sales: {"bicycle": 2, "skateboard": 5}, shop_id: 6321 }, { sales: {"bicycle": 1, "skateboard": 3}, shop_id: 6243 }, { sales: {"bicycle": 3, "skateboard": 4}, shop_id: 6243 } ]; // Output of input.reduce is an object. To get array we simply just use the values in this object const output = Object.values( // Array.prototype.reduce loops through the array // And ads all the values into the acumulator by running your custom function input.reduce( // Custom accumulator function (accumulator, value) => { // If there's already an object at this position (position is the unique shop_id) if (accumulator[value.shop_id]) { // Merge the old and the new object // Loop through all the keys of the new object Object.entries(value.sales).forEach( ([key, number]) => { // If this key is already present in the old object if (accumulator[value.shop_id].sales[key]) { // Sum the old and the new value accumulator[value.shop_id].sales[key] += number; } else { // Set the key to the new value accumulator[value.shop_id].sales[key] = number; } } ); // There is no object yet at this position } else { // Make a deep copy to avoid modifiing the input // And put it at this position accumulator[value.shop_id] = { shop_id: value.shop_id, sales: {...value.sales }, }; } // Return the modified acumulator return accumulator; }, {} //The initial accumulator (empty object) ) ); console.log(output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.