我想遍历此对象并将具有最高属性值的键返回到数组中。
Object {clear-spring: 3, deep-autumn: 2, warm-spring: 1, light-summer: 2, light-spring: 2, clear-summer: 3}
在这种情况下,我想要一个这样的数组:
["clear-summer", "clear-spring"]
使用jQuery或纯javascript有没有一种有效的方法呢?
答案 0 :(得分:2)
您只需要对项目进行一次迭代,跟踪到目前为止您发现的最大集合。
var a = {'clear-spring': 3, 'deep-autumn': 2, 'warm-spring': 1, 'light-summer': 2, 'light-spring': 2, 'clear-summer': 3};
var max = {
val: Number.NEGATIVE_INFINITY,
keys: []
}
for (var prop in a) {
if (a.hasOwnProperty(prop)) {
var n = a[prop];
if (n >= max.val) {
if (n > max.val) {
max.keys = [];
}
max.val = n;
max.keys.push(prop);
}
}
}
答案 1 :(得分:0)
您可以使用for.. in循环浏览对象
var object = {clear-spring: 3, deep-autumn: 2, warm-spring: 1, light-summer: 2, light-spring: 2, clear-summer: 3};
// Iterates over the oject
for (var key in object) {
if(object.hasOwnProperty(key)) {
// Key === 'clear-spring' (sample)
// object[key] === 3 (sample)
// do whatever you want
}
}
答案 2 :(得分:0)
var o = {'clear-spring': 3, 'deep-autumn': 2, 'warm-spring': 1, 'light-summer': 2, 'light-spring': 2, 'clear-summer': 3};
var max = 0, result = [];
// find max:
for(var k in o) { if (o[k] > max) max = o[k] }
// find keys matching the max:
for(var k in o) { if (o[k] === max) result.push(k) }
// log result
console.log(result);
答案 3 :(得分:0)
不确定是否效率最高,但首先找到最大值,然后返回并拉出所有匹配最大值的值。
var obj = {'clear-spring': 3, 'deep-autumn': 2, 'warm-spring': 1, 'light-summer': 2, 'light-spring': 2, 'clear-summer': 3};
var ary = [];
var max = Number.NEGATIVE_INFINITY;
for (var prop in obj) {
if (obj[prop] > max) {
max = obj[prop];
}
}
for (var prop in obj) {
if (obj[prop] === max) {
ary.push(prop);
}
}