简体   繁体   English

从对象数组获取唯一值及其数量

[英]Get unique values and their amounts from an array of objects

So I get a JSON request that sends an array of objects with two properties, I need to extract the unique values and their quantities. 因此,我得到一个JSON请求,该请求发送具有两个属性的对象数组,我需要提取唯一值及其数量。

This is the JSON that is being sent via Postman: 这是通过邮递员发送的JSON:

[
    {"name": "First value", "amount": 2},
    {"name": "Second value", "amount": 4},
    {"name": "First value", "amount": 6}  
]

I need to return a JSON response with the unique values and their totals added up: 我需要返回一个包含唯一值及其总计的JSON响应:

The object should look like this: 该对象应如下所示:

{
   "First value": 8,
   "Second value": 4
}

You can use reduce() 您可以使用reduce()

 const arr = [ {"name": "First value", "amount": 2}, {"name": "Second value", "amount": 4}, {"name": "First value", "amount": 6} ] const res = arr.reduce((ac, {name, amount}) => { ac[name] = ac[name] || 0; ac[name] += amount; return ac; },{}) console.log(res) 

Explanation: 说明:

First of all we are initializing ac to an empty object {} . 首先,我们将ac初始化为一个空对象{} See the line 看线

arr.reduce((ac, {name, amount}) => {...}
                ^^^^^^^^^^^^^^ 

The highlighted part is called Object destructuring. 突出显示的部分称为对象解构。 It will get the property name and amount out the current object through which we are iterating and make it independent variables. 它将获得属性name并增加当前对象的amount ,我们将通过该对象进行迭代并将其设为独立变量。

See the line 看线

ac[name] = ac[name] || 0;

Now this line is checking if ac[name] doesn't exist on the ac object then it will be undefined so undefined || 0 现在,此行正在检查ac对象上是否不存在ac[name] ,那么它将是undefined因此undefined || 0 undefined || 0 will be evaluate to 0 . undefined || 0将被评估为0 If it will have a value the value of ac[name] will remain as previous. 如果具有值,则ac[name]的值将保持先前的值。

See the third line: 参见第三行:

ac[name] += amount;

This line will add the amount to already value of ac[name] 此行会将amount添加到ac[name]已有值中

At last we return ac so that it will be become initial value of ac for next iteration. 最后,我们返回ac以便它将成为ac的下一个迭代初始值。

You could also simply use Array.forEach as it is for the most part easier to understand and follow: 您也可以简单地使用Array.forEach,因为它在大多数情况下更易于理解和遵循:

 let arr = [{ "name": "First value", "amount": 2 }, { "name": "Second value", "amount": 4 }, { "name": "First value", "amount": 6 } ], obj={} arr.forEach(({name, amount}) => { obj[name] = obj[name] || 0 obj[name] += amount }) console.log(obj) 

The main difference here is that our accumulator (the obj ) is defined outside rather than "internally" as an argument to the Array.reduce function. 这里的主要区别在于, accumulatorobj )是在外部而不是“内部”定义为Array.reduce函数的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM