Using `object` as the keys of another `object` in JavaScript
May 12, 2015
Sometimes you need to use object
s for the keys of a dictionary (let’s say, another object
).
Assume this code:
var keys = [{a: 1}, {a: 2}, {a: 3}];
var dic = {};
//add a new key to the dictionary
dic[keys[0]] = 'boo';
dic[keys[1]] = 'foo';
Above code yields this result:
console.log(dic); //Object {[object Object]: "foo"}
So the dictionary doesn’t have two items because object
keys cannot be object
. You can get the item with [object Object]
string:
console.log(dic['[object Object]']); //returns `foo`
Ok, wait. Then how we can set objects as the keys of a dictionary?
ECMAScript 6 – Map
Map
feature in ES6 enables you to assign object
s as the keys of a dictionary (or another object
).
Here is the ES6 compatible of the previous example:
var keys = [{a: 1}, {a: 2}, {a: 3}];
var map = new Map();
//add a new key to the dictionary
map.set(keys[0], 'boo');
map.set(keys[1], 'foo');
And the map
variable should be:
Map {Object {a: 1} => "boo", Object {a: 2} => "foo"}
Besides, you can get the item with get
:
map.get(keys[0]); //returns `boo`
Or set a new value for one of items:
map.set([keys[0], 'new value');
Here you can read more about Map feature in ECMAScript 6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map