使用jQuery,我如何迭代一个对象,并获得具有每个值的计数的键的唯一值?
例如,对于这个数组:
var electrons = [
{ name: 'Electron1', distance: 1 },
{ name: 'Electron2', distance: 1 },
{ name: 'Electron3', distance: 2 },
{ name: 'Electron4', distance: 2 },
{ name: 'Electron5', distance: 2 },
{ name: 'Electron6', distance: 2 },
{ name: 'Electron7', distance: 2 },
{ name: 'Electron8', distance: 2 },
{ name: 'Electron9', distance: 2 },
{ name: 'Electron10', distance: 2 },
{ name: 'Electron11', distance: 3 },
];
我想取回以下内容:
var distance_counts = {1: 2, 2: 8, 3: 1};
我有这个,虽然有效,但有点笨拙:
var radius_counts = {};
for (var i = 0; i < electrons.length; i++) {
if (electrons[i].distance in radius_counts) {
radius_counts[electrons[i].distance] += 1;
} else {
radius_counts[electrons[i].distance] = 1;
}
}
答案 0 :(得分:7)
您可以将map用于此目的:
var distances = {};
$.map(electrons,function(e,i) {
distances[e.distance] = (distances[e.distance] || 0) + 1;
});
或
var distances = {};
$.each(electrons,function(i,e) {
distances[this.distance] = (distances[this.distance] || 0) + 1;
});
我也可以向你指出,虽然这个代码看起来很好看并且紧凑,但这通常不会更快。更好地使您的代码更快,更容易看作:
var distances = {},e;
for (var i = 0,l=electrons.length; i < l; i++) {
e = electrons[i];
distances[e.distance] = (distances[e.distance] || 0) + 1;
}