将对象数组中的现有值减少为单个对象

时间:2017-07-29 21:15:29

标签: javascript jquery underscore.js lodash

我有一系列对象如下: -

arr = [{"one" :{..., details:{bikes: 5, cars: 10}}},
{"one" : {..., details:{bikes: 7, cars: 32}}},
{"one": {..., details:{bikes: 8, cars: 18}}},
{"one" : {..., details:{bikes: 9, cars: 20}}}]

现在,我想要一个结果将遍历所有这些对象,并检查细节并计算最多的自行车和汽车。

因此,输出应为: -

output = {bikes:9, cars: 32} as highest bikes count is 9 and highest cars count is 32.

我可以遍历数组并为自行车和汽车保留两个计数器变量,并在我找到更高的值时不断更新。

但我想用更短的方式使用下划线或lodash

4 个答案:

答案 0 :(得分:0)

在简单的ES6 JavaScript中:

Traceback (most recent call last):
  File "JiraTest.py", line 7, in <module>
    jira = JIRA(options)
  File "C:\Anaconda3\lib\site-packages\jira\client.py", line 317, in __init__
    si = self.server_info()
  File "C:\Anaconda3\lib\site-packages\jira\client.py", line 1771, in server_info
    j = self._get_json('serverInfo')
  File "C:\Anaconda3\lib\site-packages\jira\client.py", line 2172, in _get_json
    r = self._session.get(url, params=params)
  File "C:\Anaconda3\lib\site-packages\jira\resilientsession.py", line 150, in get
   return self.__verb('GET', url, **kwargs)
  File "C:\Anaconda3\lib\site-packages\jira\resilientsession.py", line 146, in __verb
    raise_on_error(response, verb=verb, **kwargs)
  File "C:\Anaconda3\lib\site-packages\jira\resilientsession.py", line 56, in raise_on_error
    r.status_code, error, r.url, request=request, response=r, **kwargs)
jira.exceptions.JIRAError: JiraError HTTP 404 url:https://jira.mycompany.com/rest/api/2/rest/api/2/serverInfo

        response headers = {'Date': 'Sat, 29 Jul 2017 22:42:31 GMT', 'Content-Length': '0', 'Server': 'Apache-Coyote/1.1'}
        response text = 

答案 1 :(得分:0)

这些非常简单的单行

result = {
    bikes: Math.max(...arr.map(o => o.one.details.bikes)),
    cars: Math.max(...arr.map(o => o.one.details.cars)),
};

答案 2 :(得分:0)

您可以使用Math.max来解决正确的属性。

&#13;
&#13;
$scope.mouseEnter = function(){
  console.log('enter');
};
$scope.mouseLeave = function(){
  console.log('leave');
};
&#13;
&#13;
&#13;

答案 3 :(得分:0)

使用Lodash的_.maxBy

var output = {
  bikes: _.maxBy(arr, 'one.details.bikes'),
  cars: _.maxBy(arr, 'one.details.cars')
};