Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are two different keys overriding each other in an object?

Tags:

javascript

I have the following three variables assigned:

const a = {key:true}
const b = {key:false}
const c = {[a]:'1',[b]:'2'}

When I then try to logged the following into the console:

console.log(c[a],c[b])

I got the following:

2 2

When I thought I should get:

1 2

Why am I wrong and how can I fix it?

like image 878
Stav Alfi Avatar asked Jan 04 '19 21:01

Stav Alfi


1 Answers

Objects can only have strings (or symbols) as their keys. If you try to use a non-string, it gets converted to a string. So when you set c[a] to be 1, a is an object which means it needs to be converted to a string. So you end up setting c["[object Object]"] to be one. Then when you set c[b], you do the same thing, again converting to "[object Object]" and thus overriding the value that's already there.

Try logging out c to see this:

const a = {key:true}
const b = {key:false}
const c = {[a]:'1',[b]:'2'}
console.log(c);

It's unusual to need to use objects as keys, but if you need it, you can use Maps instead of objects

const a = {key:true}
const b = {key:false}
const c = new Map();
c.set(a, '1');
c.set(b, '2');
console.log(c.get(a));
console.log(c.get(b));
like image 67
Nicholas Tower Avatar answered Oct 03 '22 16:10

Nicholas Tower