2017-05-08 51 views
0

我有對象nodes,其中每個組件對象具有.id屬性的陣列的嵌套陣列(矩陣),並且我想創建正方形matrix其是由[id][id]索引的嵌套數組代表節點到節點的相互作用:D3 JS:創建從一個扁平陣列

nodes.forEach(function(node, i) { 
    matrix[node.id] = nodes.forEach(
     function(node1, j) { 
      console.log(i,j); 
      return { 
       "x": j, 
       "y": i, 
       "z": 0 
      }; 
    }); 
    console.log(i, matrix[node.id]); 
}); 

在我收到的控制檯:

... 
149 1 
... 
149 148 
149 149 
149 undefined 

爲什麼對象是不是在表達matrix[node.id] = ...分配?爲什麼沒有錯誤或警告?我該如何解決它?


UPD:以下@pilotcam解釋是forEach沒有返回值,我嘗試以下操作:

var matrix = []; 
var testnodes = [{id: "aaa", a:10}, 
       {id: "aab", a:20}, 
       {id: "aac", a:30}, 
       {id: "aba", a:40}] 

testnodes.forEach(function(node, i) { 
    matrix[node.id] = []; 
    // [{x: 1, y:2, z:0}, {x:2,y:3,z:0}]; 
    testnodes.forEach(
     function(node1, j) { 
      matrix[node.id][node1.id] = { 
       x: j, 
       y: i, 
       z: 0 
      }; 
     console.log(i,j, node.id, node1.id, matrix[node.id][node1.id]); 
    }); 
    console.log(i, matrix[node.id]); 
}); 

不過我matrix是沒有得到填充在內循環:

... 
3 1 aba aab Object { x: 1, y: 3, z: 0 } 
3 2 aba aac Object { x: 2, y: 3, z: 0 } 
3 3 aba aba Object { x: 3, y: 3, z: 0 } 
3 Array [ ] 
+0

似乎爲我工作。查看https://jsfiddle.net/6gxvyncf/ – pilotcam

+0

後[添加螢火蟲插件](http://stackoverflow.com/questions/17382200/print-var-in-jsfiddle),我得到相同的輸出與上面的小提琴;(你在小提琴中得到了什麼輸出?你可以將它發佈在你的答案中嗎? –

+0

矩陣在任何一個循環內似乎都沒有被修改 –

回答

2

javascript forEach方法不會返回值。你可能想要做

matrix[node.id] = []; 

...並在第二個forEach內部操作。從提出的問題,我猜你想是這樣的:

nodes.forEach(function(node, i) { 
    matrix[node.id] = []; 
    nodes.forEach(
     function(node1, j) { 
      console.log(i,j); 
      matrix[node.id][node1.id] = { 
       "x": j, 
       "y": i, 
       "z": 0 
      }; 
    }); 
    console.log(i, matrix[node.id]); 
}); 

我修改了小提琴通過您的哈希表循環,並表明它可能做你想要什麼。 https://jsfiddle.net/rtxbzove/

+0

謝謝!它是有道理的,但它仍然不起作用,請參閱更新 –

1

問題是我嘗試索引一個非整數值的數組。正確的方法似乎使用 '對象'/哈希表:

var matrix = {}; 
var testnodes = [{id: "aaa", a:10}, 
       {id: "aab", a:20}, 
       {id: "aac", a:30}, 
       {id: "aba", a:40}] 

// with simple for loops: 
for (var i = 0, len = testnodes.length; i < len; i++) { 
    matrix[testnodes[i].id] = {}; 
    for (var j = 0, len = testnodes.length; j < len; j++) { 
    matrix[testnodes[i].id][testnodes[j].id] = { 
       x: j, 
       y: i, 
       z: 0 
      }; 
    } 
    console.log("matrix:", matrix[testnodes[i].id]); 
} 
console.log("matrix:", matrix); 

或者,forEach循環:

testnodes.forEach(function(node, i) { 
    matrix[node.id] = {}; 
    testnodes.forEach(
     function(node1, j) { 
      console.log(i,j); 
      matrix[node.id][node1.id] = { 
       "x": j, 
       "y": i, 
       "z": 0 
      }; 
    }); 
    console.log(i, matrix[node.id]); 
});