繁体   English   中英

使用 object 的属性对数组进行索引时,Javascript 返回 undefined

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

我正在尝试使用数组中的 object 的属性来检索邻居节点。 我无法在节点数组中使用链接索引的属性。 我想知道如何修改const a的代码以检索值? 任何帮助表示赞赏!

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);
      });

这是我控制台记录的值: 记录值

问题是gData.nodes是一个数组 object - 它的键是“0”、“1”、“2”,而不是数组中条目的id属性值。

解决此问题的一种简单方法(缩短或重组对象的内容)是使用 id 值作为索引键创建查找表:

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

然后在需要时从它们的id查找节点:

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

另一种解决方案可能是为gData object 编写getNodeById方法。

一旦为 a 和 b 分配了正确的节点值,由未定义的ab值生成的语法错误应该自行解决。 显然,如果在运行时可能出现错误情况,那么也应该包含错误处理代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM