【问题标题】:How to compare between object elments values in javascript如何在javascript中比较对象元素值
【发布时间】:2017-04-20 07:41:35
【问题描述】:

如何在 javascript 中比较对象元素的值

例如:

var obj = { tom: "5000", justin: "500", linda: "3000" };

我如何编写代码来知道哪个人的薪水更高,如示例中所示:我应该在这里得到结果 (tom)?

【问题讨论】:

    标签: javascript node.js object compare


    【解决方案1】:

    您可以首先使用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() 以从字符串中获取数字。
    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多