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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With