I want to make an array of parent and another array of children, and later set an array of children to each parent.
Here is the code:
var parent = [];
var child = [];
// Set kids
for (a = 0; a <= 5; a++) {
child[a] = [];
child[a].name = "kid " + a;
}
// Set parents and their kids
for (b = 0; b < 2; b++) {
parent[b] = [];
parent[b].name = "parent " + b;
parent[b].kids = child;
}
// One parent has kid name anna
parent[0].kids[2].name = "anna";
// Output
for (a = 0; a < 2; a++) {
console.log("");
for (b = 0; b < 5; b++) {
console.log(b + " -> " + parent[a].name + " " + parent[a].kids[b].name);
}
}
First parent
0 -> parent 0 kid 0
1 -> parent 0 kid 1
2 -> parent 0 anna
3 -> parent 0 kid 3
4 -> parent 0 kid 4
Second parent
0 -> parent 1 kid 0
1 -> parent 1 kid 1
2 -> parent 1 anna
3 -> parent 1 kid 3
4 -> parent 1 kid 4
Why do both parent have the same children only first one should have the kid name anna, and more important How can I make it to work properly?
childarray. Objects and arrays are passed by reference not value in JS. Also you are probably wanting to create an object and not an array for each new partent/child i.e.parent[b] = {};instead ofparent[b] = [];parent[b].kids = child;. So allkindsare the same object reference tochildobject.