I'm trying to create an Object with HTML elements as keys. I create the keys using document.createElement('div')
, but when I try to insert both into an Object the second key ends up replacing the first:
let a = document.createElement('div');
let b = document.createElement('div');
let obj = {};
obj[a] = 3;
obj[b] = 'x';
console.log(obj);
I'm trying to create an Object with HTML elements as keys. I create the keys using document.createElement('div')
, but when I try to insert both into an Object the second key ends up replacing the first:
let a = document.createElement('div');
let b = document.createElement('div');
let obj = {};
obj[a] = 3;
obj[b] = 'x';
console.log(obj);
Is there a way to do this without any keys or values getting replaced?
Share Improve this question edited Feb 15, 2021 at 14:40 pretzelhammer 15.2k16 gold badges53 silver badges103 bronze badges asked May 22, 2020 at 14:16 ketanketan 19.4k42 gold badges68 silver badges104 bronze badges 9- 1 what are you trying to do , what is your use case ? – ashish singh Commented May 22, 2020 at 14:18
-
1
You could use
Map
instead of an plain object. – Sirko Commented May 22, 2020 at 14:18 - This question was asked me on interview. But, couldn't find answer. – ketan Commented May 22, 2020 at 14:22
- 1 What exactly was the interview question? Pretty sure you misunderstood what they wanted. – Guy Incognito Commented May 22, 2020 at 14:25
-
1
Whenever a key is added to an object, it internally does
String(key)
. BothString(a)
andString(b)
return"[object HTMLDivElement]"
. It's still unclear what the question is. Did your interview ask how can we use an HTML element as the key of an object? – adiga Commented May 22, 2020 at 14:32
2 Answers
Reset to default 9Objects can only hold string keys. Your div
s are being serialized to strings and then overriding each other. If you would like to hold HTML Elements as keys you should use a Map like so:
let a = document.createElement('div');
let b = document.createElement('div');
let map = new Map();
map.set(a, 3);
map.set(b, 'x');
// use Array.from to pretty print the result
console.log(Array.from(map));
When you use a
to create a key in an object
let a = document.createElement('div');
obj[a] = 3;
It assigns the object
the string representation of a
which is "[object HTMLDivElement]"
console.log(obj); // { "[object HTMLDivElement]": 3 }
So when you assign b
obj[b] = 'x';
what you're really saying is
obj["[object HTMLDivElement]"] = 'x'
and "[object HTMLDivElement]"
already exists in the object, so it assigns it the new value of 'x'
console.log(obj); // { "[object HTMLDivElement]": "x" }