Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript object as object key

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.

like image 762
Dexygen Avatar asked Jul 24 '26 23:07

Dexygen


1 Answers

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'
like image 121
idbehold Avatar answered Jul 27 '26 11:07

idbehold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!