d3 force graph using node names for links <p>I've been at this for a few days now, and I've seen the questions on stackoverflow and other places, but I am missing something.</p> <p>Lets say we have the following JSON:</p> <pre><code>{ "nodes":[ {"name":"node1"}, {"name":"node2"}, {"name":"node3"}, {"name":"node4"} ], "links":[ {"source":"node1","target":"node2"}, {"source":"node1","target":"node3"}, {"source":"node1","target":"node4"} ] } </code></pre> <p>Why do the following two pieces of code yield the same output in the console, but the second gives me an error (Uncaught TypeError: Cannot read property 'push' of undefined)?</p> <pre><code>links = links.map(function(l) { var sourceNode = nodes.filter(function(n) { return n.name === l.source; })[0]; var targetNode = nodes.filter(function(n) { return n.name === l.target; })[0]; return { source: sourceNode, target: targetNode }; }); </code></pre> <p>_ </p> <pre><code>links.forEach(function(link) { link.source = {name: link.source}; link.target = {name: link.target}; }); </code></pre> <p>Console output:</p> <pre><code>[{"source":{"name":"node1"},"target":{"name":"node2"}}, {"source":{"name":"node1"},"target":{"name":"node3"}}, {"source":{"name":"node1"},"target":{"name":"node4"}}] </code></pre>