【问题标题】:Using Javascript object as object key使用 Javascript 对象作为对象键
【发布时间】:2015-05-13 09:19:32
【问题描述】:

我正在尝试设计一种方法来使用一个简单的 Javascript 对象(一级深度键值对)作为另一个对象的键。我知道仅使用对象而不进行字符串化将导致 [Object object] 被用作键;请参阅以下内容:Using an object as a property key in JavaScript(所以这个问题不是重复的)。

a blog post about it 考虑到了这一点,也考虑了按对象键排序的需要,因为它们的顺序不能保证,但包含的 Javascript 代码运行超过 100 行。我们正在使用 underscore.js 库,因为它与主干密切相关,但纯 Javascript 替代方案也将引起人们的兴趣。

【问题讨论】:

    标签: javascript object key underscore.js


    【解决方案1】:

    在 ECMAScript 6 中,您将能够使用 Maps

    var map = new Map();
    
    var keyObj = { a: "b" },
        keyFunc = function(){},
        keyString = "foobar";
    
    // setting the values
    map.set(keyObj,    "value associated with keyObj");
    map.set(keyFunc,   "value associated with keyFunc");
    map.set(keyString, "value associated with 'foobar'");
    
    console.log(map.size);              // 3
    
    // getting the values
    console.log(map.get(keyObj));       // "value associated with keyObj"
    console.log(map.get(keyFunc));      // "value associated with keyFunc"
    console.log(map.get(keyString));    // "value associated with 'a string'"
    
    console.log(map.get({ a: "b" }));   // undefined, because keyObj !== { a: "b" }
    console.log(map.get(function(){})); // undefined, because keyFunc !== function(){}
    console.log(map.get("foobar"));     // "value associated with 'foobar'"
                                        // because keyString === 'foobar'

    【讨论】:

      【解决方案2】:

      我编写了一个接受任意键的哈希表实现,但我怀疑你会因为文件相对较大而拒绝它。

      https://code.google.com/p/jshashtable/

      【讨论】:

        【解决方案3】:

        这是一个基于下划线的解决方案,它依赖于首先将对象转换为键值对。

        var myObj = { name: 'john', state: 'ny', age: 12};
        var objPairs = _.pairs(myObj);
        
        var sortedPairs = _.reduce(_.keys(myObj).sort(), function(sortedPairs, key) {
            var pair = _.find(objPairs, function(kvPair) {return kvPair[0] == key});
            sortedPairs.push(pair);
            return sortedPairs;
        }, []);
        
        console.log(JSON.stringify(sortedPairs)); //stringifying makes suitable as object key
        // [["age",12],["name","john"],["state","ny"]]
        

        【讨论】:

          【解决方案4】:

          你可以使用这样的模式。这样一来,对象的键就是您为每个对象生成的随机 id。

          var MyObject = function(name) {
              this.name = name;
              this.id = Math.random().toString(36).slice(2);
          }
          
          MyObject.prototype.toString = function() {
              return this.id;
          }
          

          【讨论】:

            猜你喜欢
            • 2022-01-25
            • 1970-01-01
            • 1970-01-01
            • 2021-10-23
            • 2016-04-09
            • 2022-08-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多