Reputation: 5796
I have two objects. When I pass these as key to an associative array, and assign a value, all the values are stored wrong ( except for the last one ).
Can anyone please tell me what I'm doing wrong ??
var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};
var comm = {};
comm[usrMrid] = "ONE";
comm[usrXYZZ] = "TWO";
console.log("usrMrid: " + comm[usrMrid]); // this gives TWO, when it should give ONE
console.log("usrXYZZ: " + comm[usrXYZZ]); // this works fine
Upvotes: 1
Views: 65
Reputation: 1609
well this has a problem, when you write an object in associative array style it only accepts strings. In your case it will overwrite itself and will always have the same answer for both the objects,
you need to write something like this otherwise it will always overwrite it.
var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};
var comm = {};
comm[usrMrid.name] = "ONE";
comm[usrXYZZ.name] = "TWO";
console.log(comm);// this will print your object correctly.
console.log(comm[usrMrid.name]);// this will print ONE
console.log(comm["mrid"]);// this will also print ONE
console.log(comm["xyzz"]); // This will print TWO
console.log(comm[usrXYZZ.name]); // This will print TWO
Upvotes: 2
Reputation: 68685
When you use []
syntax with object and you pass an object as a property name, property name is going to be the string
representation of the given expression, which will be in your case [object Object]
. So when you use different objects, they create the same property with name [object Object]
and override the previous ones.
You can see it in the example. Here I print the properties of the object and you can see that there is just one property with name [object Object]
.
var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};
var comm = {};
comm[usrMrid] = "ONE";
comm[usrXYZZ] = "TWO";
console.log(comm);
You can use Map
for that case
var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};
var comm = new Map([
[usrMrid, "ONE"],
[usrXYZZ, "TWO"]
]);
console.log(comm.get(usrMrid));
Upvotes: 7
Reputation: 138557
Object keys are String only! Use a Map for that:
var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};
const comm = new Map([
[usrMrid,"ONE"],
[usrXYZZ, "TWO"]
]);
console.log(comm.get(usrMrid));
However this is a really good usecase for Symbols too:
const id = Symbol("id");
var usrMrid = {
name: "mrid",
[id]:"ONE"
};
var usrXYZZ = {
name: "xyzz",
[id]:"TWO"
};
console.log(usrMrid, usrMrid[id]);
Upvotes: 2