Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
969 views
in Technique[技术] by (71.8m points)

d3.js - 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

question from:https://stackoverflow.com/questions/65839020/javascript-returns-undefined-when-indexing-into-an-array-using-a-property-of-an

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is that gData.nodes is an array object - its keys are "0", "1", "2", not the id property values of entries in the array.

A simple way of fixing this, short or restructuring the object's content, is to create a lookup table using the id value as the index key:

  gData.index = {};
  gData.nodes.forEach( node => gData.index[node.id] = node);

and then looking up the nodes from their id where required:

  const a = gData.index[link.source];
  const b = gData.index[link.target];

Another solution might be to write a getNodeById method for the gData object.

Syntax errors generated by undefined values for a and b should resolve themselves once they are assigned correct node values. Obviously if error conditions are possible at run time, then error handling code should be included as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...