Search code examples
javascriptarraysclassobjectkey

JavaScript: How do I add a custom class object as a key of an array


I have created a custom class with the property “name”

I also added a function to the class which returns true if 2 objects have the same name. This function works when I compare 2 custom objects with the same name.

However, I am facing problems when I added these custom class objects as keys in an array/object.

Suppose my custom class object is a. It is also a key in an array. When I compare a with the keys in the array, I get that a is not in the array.

My class constructor:

class node {
  constructor(name) {
    this.name = name;
  }
  getname() {
    return this.name;
  }
  equiv(other) {
    return Boolean(this.name == other.name);
  }
  inarray(array) {
    for (let key in array) {
      if (this.name== key.name)
      {
        return true;
      }
    }
    return false;
  }
}

var a = new node("assss");
var b = new node("bssss");
var a2 = new node("assss");

var c = {a:1, b:2}

console.log( a.equiv(a2) ) // true
//But
console.log( a.inarray(c) ) // false

a.equiv(a2) returns true
But
a.inarray(c) returns false

^ this is my issue


Solution

  • since you have upadated your question :

    just replace

    if (this.name == key.name)
    

    by

    if (this.name == key)
    

    because key is a string (not an object) and it' values are 'a' or 'b'
    they are the keys of { a:1, b:2 }

    class node {
      constructor(name) {
        this.name = name;
      }
      getname() {
        return this.name;
      }
      equiv(other) {
        return Boolean(this.name == other.name);
      }
      inarray(array) {
        for (let key in array) {
          if (this.name == key)
          {
            return true;
          }
        }
        return false;
      }
    }
    
    var a  = new node("a")
      , b  = new node("b")
      , a2 = new node("a")
      , c  = { a:1, b:2 }
      ;
    console.log( a.equiv(a2) ) // true
    console.log( a.inarray(c) ) // true