Using Javascript object as object key

2019-08-28 00:40发布

I am trying to devise a way to use a simple Javascript object (one level deep key value pairs) as a key to another object. I am aware that merely using the object without stringification will result in [Object object] being used as the key; see the following: Using an object as a property key in JavaScript (so this question is not a duplicate).

There is a blog post about it that takes this into account and also accounts for the need to sort by object key since their order is not guaranteed, but the included Javascript code runs over a 100 lines. We are using the underscore.js library since that goes hand in hand with backbone but pure Javascript alternatives will also be of interest.

3条回答
疯言疯语
2楼-- · 2019-08-28 01:27

I wrote a hash table implementation that accepts arbitrary keys but I suspect you'll reject it on the grounds of the relatively large file size.

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

查看更多
在下西门庆
3楼-- · 2019-08-28 01:27

Here is an underscore based solution that relies on first converting the object to key-value pairs.

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"]]
查看更多
你好瞎i
4楼-- · 2019-08-28 01:35

In ECMAScript 6 you'll be able to use 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'

查看更多
登录 后发表回答