Something odd going on with JavaScript object maps

I am facing an issue with two objects that I am trying to store in an associative array. When I assign values to them, all the values are stored incorrectly, except for the last one.

Can someone please help me figure out what I am 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

Answer №1

When you utilize the `[ ]` syntax with an object and pass an object as a property name, the property name will be the string representation of the given expression. In this case, it will be `[object Object]`. Therefore, using different objects will create the same property with the name `[object Object]` and override the previous ones.

This behavior is evident in the provided example. The properties of the object are printed, revealing only one property named `[object Object]`.

var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};

var comm = {};

comm[usrMrid] = "ONE";
comm[usrXYZZ] = "TWO";

console.log(comm);

To avoid this issue, you can utilize a `Map` in such cases.

var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};

var comm = new Map([
  [usrMrid, "ONE"],
  [usrXYZZ, "TWO"]
]);

console.log(comm.get(usrMrid));

Answer №2

Keys in objects must be Strings! Consider using a Map instead:

var userMrid = {name: "mrid"};
var userXYZZ = {name: "xyzz"};

const communication = new Map([
  [userMrid,"ONE"],
  [userXYZZ, "TWO"]
]);

console.log(communication.get(userMrid));

Alternatively, Symbols can also be a great solution for this scenario:

 const id = Symbol("id");

var userMrid = {
  name: "mrid",
  [id]:"ONE"
};
var userXYZZ = {
   name: "xyzz",
    [id]:"TWO"
};

 console.log(userMrid, userMrid[id]);

Answer №3

There seems to be an issue here. When using the associative array style to write an object, it only accepts strings. This means that in your current setup, the objects will overwrite each other and always have the same answer.

To avoid this, you should structure your code differently. Try something like this to prevent overwriting:

var userMrid = {name: "mrid"};
var userXYZZ = {name: "xyzz"};

var communication = {};

communication[userMrid.name] = "ONE";
communication[userXYZZ.name] = "TWO";

console.log(communication); // This will display the object correctly.
console.log(communication[userMrid.name]); // This will show "ONE"
console.log(communication["mrid"]); // This will also show "ONE"
console.log(communication["xyzz"]); // This will display "TWO"
console.log(communication[userXYZZ.name]); // This will show "TWO"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for avoiding divs from overlapping when the window size is modified

When I maximize the browser, everything aligns perfectly as planned. However, resizing the window causes my divs to overlap. Despite trying several similar posts on this issue without success, I have decided to share my own code. CODE: $(document).read ...

Is it the browser's responsibility to convert ES6 to ES5 internally?

Given the support for ES6 in modern browsers, do they internally convert ES6 to ES5 before executing the code? Or can they process ES6 natively using a C++ engine? If they are able to run ES6 directly, how do they guarantee that executing ES6 code produce ...

Images within inline blocks appear to be extending beyond their containing div as though they are

When I check my website in various browsers such as Firefox, IE, Edge, and Safari, I noticed that the images in the "My Specialties" section of the left column are extending outside of the div instead of fitting within it. This problem also occurs in Chrom ...

Optimal strategies for designing navigation bars on contemporary websites

Struggling to find a solid answer for this dilemma. I have multiple html pages and a single navigation bar that I want to include on all pages for consistency. The idea of duplicating the html code for the navigation bar goes against everything I've l ...

Is it possible to generate grid options dynamically for various tables within AngularJS using ui-grid?

I have developed a service for ui-grid table functionality. Currently, I am able to use this service on a single page but now I want to extend its usage to multiple pages, each with different table data. How can I pass grid options and JSON data for multip ...

Shut down the active tab

For some reason, using window.close(); in my JavaScript script is not closing the currently opened tab as expected. I'm looking for a way to automatically close a manually opened tab using a JavaScript function. Any ideas on what might be going wrong? ...

Error encountered while using XLSX.write in angular.js: n.t.match function is not recognized

I've encountered an issue while trying to generate an .xlsx file using the XLSX library. The error message I received is as follows: TypeError: n.t.match is not a function at Ps (xlsx.full.min.js:14) at Jd (xlsx.full.min.js:18) at Sv (xlsx.full.min ...

A guide on accessing a particular element within an array using MikroC

I'm having trouble working with an array in MikroC. The array I'm trying to work with is defined as follows: char array[4] = {'1','1','0','\0'}; My goal is to extract a specific element from ...

Error: Unable to access the 'ht_4year_risk_opt' property because it is null

When attempting to call the servlet that returns JSON data, I encounter an error while parsing the data. var jsonResponse = jQuery.parseJSON(data); var ht_4year_risk_opt = jsonResponse.ht_4year_risk_opt; ...

What is the method for combining two SC.RecordArray instances in Sproutcore?

Below is the code snippet : queryTree = SC.Query.local('Tree.Category', "categoryId = {categoryId}", { categoryId: this.get('guid'), orderBy: "name ASC" }); queryNote = SC.Query.l ...

The absence of a form data boundary in the content-type of the POST request header

I have encountered an issue with my file upload code in AngularJS. The boundary is not being added to the content-type property in the request header, causing my C# web-api function to fail in detecting the image. Here's the post request using angula ...

Adding routes dynamically in nodeJS using Express is a powerful way to manage your server

Is there a way to dynamically add paths to nodeJS within a running program? Instead of relying on kludged solutions like resetting the server when files change, I am looking for a more efficient method. Any suggestions? EDIT: This project is focused on pr ...

What is the best way to iterate over an indexed attribute in PHP?

Here is my ajax code snippet: $.ajax({ type: "POST", url: "bee_sesi_edit.php", data: 'serv_ruang='+ serv_ruangx +'&who='+names +'&sesi_d1='+ sesi_d1 +&apos ...

Creating basic pairings in PHP

Our school network consists of 3 branches: xschool atlanta xschool ortigas xschool bagio I am looking to create various combinations using these branches. How can I generate the following array in PHP? ...

props remain undefined even after being assigned in the redux store

I encountered an unusual error related to a reducer called prs when adding or deleting a person in an app. Essentially, this app allows users to add or remove a person with a unique ID assigned to each individual. To start off, here is the parent componen ...

Extension: What is the best way to leverage data obtained from an ajax request in order to dynamically modify an already existing element within

I've been trying to find a reliable and comprehensive tutorial for JavaScript (JS) and Ajax, but so far my search has been futile. Unlike Python.org for Python or php.net for PHP, I haven't found a satisfactory resource yet. Any recommendations w ...

Is it viable to execute a reload on the same location and subsequently activate a click function?

Is it possible to combine a click function with a location reload and then trigger another click function? Please see the code example below: $('.ui-button').click(function () { location.reload(); $('#Sites').t ...

What is the best way to update specific values in a react multiselect component?

Within my modal, I have a form where I can edit my model. One of the fields in this form is a multi-select tag field called "tags", which is an array of objects consisting of labels and values as illustrated below. To populate this tag field, I have a dum ...

Ways to avoid submitting based on the outcome of AJAX requests

When working on an ASP.NET MVC Project, I encountered an issue where I wanted to prevent a button from submitting if the result returned from an AJAX call was false. However, no matter what I tried, the button always triggered the submission. Below is th ...

Creating a render function that includes the img.src parameter requires careful thought and consideration

I am currently working on a dilemma where I need to dynamically adjust the height and width of an image in my render() function every time there is a state change. Here is the code snippet: render() { const imageURL = photos[this.state.currentImage]. ...