Reputation: 913
I am attempting to add two attributes to a array of objects so I decided to create a new array of objects from the original one and then set the new attributes. (I realize there are probably be easier ways of doing this.)
My problem is that when I attempt to access an attribute within the new array it is undefined. What is wrong is probably obvious but not to me. Help!
var join = [];
for (linksIndex = 0; linksIndex < links.length; ++linksIndex) {
join.push([{source:links[linksIndex].source,target:links[linksIndex].target, x1:0, y1:0, x2:0, y2:0}]);
};
for (joinIndex = 0; joinIndex < join.length; ++joinIndex) {
// console.log("join in loop");console.log(join); // ok array of objects
// console.log("join[joinIndex]");console.log(join[joinIndex]); // on object
console.log("join[joinIndex].source");console.log(join[joinIndex].source); // undefined why?
for (nodesIndex = 0; nodesIndex < nodes.length; ++nodesIndex) {
if (nodes[nodesIndex].name == join[joinIndex].source) {
join[joinIndex].x1=nodes[nodesIndex].x; // match source
join[joinIndex].y1=nodes[nodesIndex].y; // match source
};
if (nodes[nodesIndex].name == join[joinIndex].target) {
join[joinIndex].x2=nodes[nodesIndex].x; // match target
join[joinIndex].y2=nodes[nodesIndex].y; // match target
} ;
}
}
Upvotes: 0
Views: 269
Reputation: 1225
You are pushing in the array another array with an object!
so if you change it to:
join[joinIndex][0].source
it will work. But i guess this is not what you want. So change the join.push() to:
join.push({
source: links[linksIndex].source,
target: links[linksIndex].target,
x1: 0,
y1: 0,
x2: 0,
y2: 0
});
Upvotes: 0
Reputation: 36521
You're pushing arrays containing objects into your join
array. When you attempt to access x1
or x2
in the array, you're getting undefined
, because the array only has one element at 0
(which is the object you're expecting).
You need to do: join.push({source:links[linksIndex].source,target:links[linksIndex].target, x1:0, y1:0, x2:0, y2:0})
It would be easy to catch this error by using a debugger. I would put a breakpoint on the second loop, and it would be easy to see exactly what join
contains.
Upvotes: 0
Reputation: 16068
Change this:
join.push([{source:links[linksIndex].source,target:links[linksIndex].target, x1:0, y1:0, x2:0, y2:0}]);
To:
join.push({source:links[linksIndex].source,target:links[linksIndex].target, x1:0, y1:0, x2:0, y2:0});
Or use console.log(join[joinIndex][0].source);//you need to access the array you made
Upvotes: 1