【发布时间】:2017-04-20 07:41:35
【问题描述】:
如何在 javascript 中比较对象元素的值
例如:
var obj = { tom: "5000", justin: "500", linda: "3000" };
我如何编写代码来知道哪个人的薪水更高,如示例中所示:我应该在这里得到结果 (tom)?
【问题讨论】:
标签: javascript node.js object compare
如何在 javascript 中比较对象元素的值
例如:
var obj = { tom: "5000", justin: "500", linda: "3000" };
我如何编写代码来知道哪个人的薪水更高,如示例中所示:我应该在这里得到结果 (tom)?
【问题讨论】:
标签: javascript node.js object compare
您可以首先使用Object.keys 获取对象的所有键,然后通过使用Array#reduce 获取更高薪水的键来减少。
var object = { tom: "5000", justin: "500", linda: "3000" },
keys = Object.keys(object),
max = keys.reduce(function (a, b) {
return +object[a] > +object[b] ? a : b;
});
console.log(max);
要获得不止一个顶部键,您需要一种不同的方法并返回一个数组而不是单个值。
var object = { justin: "500", linda: "3000", tom: "5000", jane: "5000" },
keys = Object.keys(object),
max = keys.reduce(function (r, a, i) {
if (!i || +object[a] > +object[r[0]]) {
return [a];
}
if (+object[a] === +object[r[0]]) {
r.push(a);
}
return r;
}, []);
console.log(max);
【讨论】:
object 类似于{ tom: "5000", justin: "500", linda: "3000", tim: "10000" },则会产生不正确的结果。我建议添加parseInt() 以从字符串中获取数字。
function getMaxUser(object) {
let maxUser = { max: 0 }
for (let user in object) {
if (maxUser.max < object[user]) {
maxUser = {
max: object[user],
user: user
}
}
}
return maxUser
}
var obj = { tom: "5000", justin: "500", linda: "3000" }
console.log(getMaxUser(object).user) //tom
【讨论】: