0

let obj = {};
            obj[{key:"instagram"}] = "Akrixa";
            obj[{key:"facebook"}] = "Coding with Akrixa";

            console.log(obj[{key: "instagram"}]);

This is a problem in which I'm confused with 2nd and 3rd line of code, what does by those lines?

3 Answers3

2

obj[{key:"instagram"}] = "Akrixa" is equivalent to obj[({key:"instagram"}).toString()] = "Akrixa" since objects are keyed by strings. So it's equivalent to obj["[object Object]"] = "Akrixa"

bel3atar
  • 913
  • 4
  • 6
0

I think because obj[{key:"instagram"}] and obj[{key:"facebook"}] are the same object. When assign value for it, it has the same value. More detail: How to create dictionary and add key–value pairs dynamically?. I wish its help you

Tiến Lê
  • 11
  • 3
-1

The second line obj[{key:"instagram"}] = "Akrixa"; creates a key within your obj [{key:"instagram}] (which is an object inside an array) and then sets the value of that key to Akrixa, and the third line does the same but with a different key and value.

It might be better to use obj["instagram"] = "Akrixa" and obj["facebook"] = "Coding with Akrixa" as to avoid excessive complication, and you can then refer to it with obj["instagram"] etc.

let obj = {};
obj["instagram"] = "Akrixa";
obj["facebook"] = "Coding with Akrixa";
console.log(obj["instagram"]);
Joe
  • 69
  • 4