使用 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;
}
}