Javascript returns undefined when indexing into an array using a property of an object

I’m trying retrieve neighbor nodes using a property of an object in an array. I’m unable to use a property of an link index into the node array. I’m wondering how I can modify the code for const a to retrieve a value? Any help is appreciated!

const gData = {
        nodes: [
          {id: "John"},
          {id: "Jack"},
          {id: "Jim"}
        ],
        links: [
          {source: "John", target: "Jim"},
          {source: "John", target: "Jack"},
          {source: "Jack", target: "Jim"}
        ]
      }
    
      // cross-link node objects
      gData.links.forEach(link => {
        
        const a = gData.nodes[link.source]; // returns undefined
        const b = gData.nodes[link.target];


        console.log("nodes in graph data ", gData.nodes)
        console.log("link", link)
        console.log("link.source", link.source)
        console.log("index into nodes  ", gData.nodes[link.source])
        
        !a.neighbors && (a.neighbors = []);
        !b.neighbors && (b.neighbors = []);
        
        a.neighbors.push(b);
        b.neighbors.push(a);
  
        !a.links && (a.links = []);
        !b.links && (b.links = []);
        
        a.links.push(link);
        b.links.push(link);
      });

Here are the values I console.logged:
logged values

49 thoughts on “Javascript returns undefined when indexing into an array using a property of an object”

  1. Pingback: ivermectay 6 mg

Leave a Comment