Search code examples
javascriptarraysnestedjavascript-objects

How to :Retrieve & check nested Objects in an Array


I have the following issue that I was not able to solve for the last couple of days.

So I have a class called "Nodes" which has the property Neighbors - which is an Array.

When I insert into a Node (Node A) a Node(Node B) as a "Neighbor" into the Neighbors array, it has to be an instance of the Class Neighbors that takes the instance of Node B as a parameter as an "opposite node".

Now I have to create a Statement that checks if this connection between Node A and B already exists or not

what is the best way to do that? I came across the method of destructuring but I am not sure if that is suited for the task.

class Node {
  constructor(nodeName) {
    this.nodeName = nodeName;
    this.neighbours = [];
  }
};

class Neighbour {
  constructor(oppositeNode, weight = null) {
    this.oppositeNode = oppositeNode;
    this.weight = weight;
  }
};

nodea = new Node(a);
nodeb = new Node(b);
nodea.neighbours.push(new Neighbour(nodeb));

So the Statement that I want to be able to write is the following:

Pseudo Code

If (NODE A has NODE B in NODE A.neighbours) {x}

Thanks in advance


Solution

  • Here is a continuation of your script with a check using the find method:

    class Node {
      constructor(nodeName) {
        this.nodeName = nodeName;
        this.neighbours = [];
      }
    };
    
    class Neighbour {
      constructor(oppositeNode, weight = null) {
        this.oppositeNode = oppositeNode;
        this.weight = weight;
      }
    };
    
    nodea = new Node("a");
    nodeb = new Node("b");
    nodea.neighbours.push(new Neighbour(nodeb));
    
    let neighbour = nodea.neighbours.find(neighbour => neighbour.oppositeNode == nodeb);
    
    if (neighbour) console.log("found neighbor. It has weight " + neighbour.weight);
    else console.log("not found");