Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript: new objects of the same class as keys for a dictionary

I tried the following, but the dictionary only had one key.

class dog
{
}
dic = {}

for(let i=0; i<3; i++)
{
    dic[new dog()] = i;
}

for(var item in dic)
{
 console.log(dic[item]);
}

But that was not what I intended. I wanted it to work like the following C# code, whose output is 0 1 2. It seems that each new dog() in the JS code above is treated as the same object and thus the value overwrites the previous one. How can I modify the JS code so that it work like the C# code below?

using System;
using System.Collections.Generic;

class dog
{
}

public class Program
{
    public static void Main()
    {
        var dic = new Dictionary<object,int>();

        for(var i=0; i<3; i++)
        {
            dic[new dog()] = i;
        }
        
        foreach(var item in dic.Keys)
        {
          Console.WriteLine(dic[item]);
        }
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Object keys can only be one of two type i.e. Strings or Symbols. To achieve the desired behaviour, you can use a Map instead of an object as a dictionary.

class Dog {
}

const map = new Map();

for (let i = 0; i < 3; i++) {
    map.set(new Dog(), i);
}

for (const [key, value] of map.entries()) {
    console.log(value);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading