Couldn't find anything about this.
I have this controller:
app.controller('StatsCtrl', function ($scope, $http) {
$http.get('stats.json').success(function(data) {
$scope.stats = data;
});
});
The stats.json has:
{"lang":{"en":28,"und":1,"ja":9,"es":14,"ru":1,"in":1,"ko":1,"th":1,"ar":1}}
What I need is to assign the maximum value from the lang
object to $scope.max
in the controller. What is the best way to do this?
https://jsfiddle.net/kaiser07/6h317Lvv/
var jsonText = '{"lang":{"en":28,"und":1,"ja":9,"es":14,"ru":1,"in":1,"ko":1,"th":1,"ar":1}}';
var data = JSON.parse(jsonText).lang
var maxProp = null
var maxValue = -1
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
var value = data[prop]
if (value > maxValue) {
maxProp = prop
maxValue = value
}
}
}
I would suggest to use underscore.js _.max
:
_.max(list, [iteratee], [context])
Returns the maximum value in list. If an iteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked. -Infinity is returned if list is empty, so an isEmpty guard may be required.
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.max(stooges, function(stooge){ return stooge.age; });
=> {name: 'curly', age: 60};
You can do it with a couple of native methods:
$scope.max = Math.max.apply(null, Object.keys(data.lang).map(function(key) {
return data.lang[key];
}));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.