I have an array of objects nodes
, where each component object has .id
property, and I would like to create a square matrix
which is a nested array indexed by [id][id]
representing node-by-node interactions:
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]);
});
In the console I am getting:
...
149 1
...
149 148
149 149
149 undefined
Why is the object is not assigned in the expression matrix[node.id] = ...
? Why there is no error or warning? How can I fix it?
Upd: following @pilotcam explanation that forEach
does not return a value, I tried following:
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]);
});
Still my matrix
is not getting filled in the inner loop:
...
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 [ ]