Could someone help me with creating an array of objects (only 1 level) based on the following JSON structure?
[
{
'family' : {
'name' : 'Doe',
'from' : 'Foo'
},
'couples' : [
{
'couple' : {
'man' : 'Joe',
'woman' : 'Jane'
},
'childrens' : [
{
'name' : 'Joseph',
'sex' : 'male'
},
{
'name' : 'Martin',
'sex' : 'male'
}
]
},
{
'couple' : {
'man' : 'Richard',
'woman' : 'Rose'
},
'childrens' : [
{
'name' : 'Rose',
'sex' : 'female'
},
{
'name' : 'Joe',
'sex' : 'male'
}
]
}
]
}
]
I want to consolidate all the children in one array (in this case, 4 elements) and update each element's __proto__
to include references to their parent elements (the children will have a reference to the couple, and the couple will have a reference to the family). This way, accessing the parents becomes easier.
I've come up with the following solution:
var childrenArr = [];
for (var i = 0; i < json.length; i++) {
var family = json[i].family;
var couples = json[i].couples;
for (var j = 0; j < couples.length; j++) {
var couple = couples[j].couple;
var childrens = couples[j].childrens;
for (var y = 0; y < childrens.length; y++) {
var children = childrens[y];
children.__proto__ = { couple : couple, family : family};
childrenArr.push(children);
}
}
}
However, I'm not entirely convinced that this is the optimal solution. Does anyone have suggestions on how I could improve this without using a framework?
Thank you!
EDIT
Below is an example using the code provided above.
var json = [
{
'family' : {
'name' : 'Doe',
'from' : 'Foo'
},
'couples' : [
{
'couple' : {
'man' : 'Joe',
'woman' : 'Jane'
},
'childrens' : [
{
'name' : 'Joseph',
'sex' : 'male'
},
{
'name' : 'Martin',
'sex' : 'male'
}
]
},
{
'couple' : {
'man' : 'Richard',
'woman' : 'Rose'
},
'childrens' : [
{
'name' : 'Rose',
'sex' : 'female'
},
{
'name' : 'Joe',
'sex' : 'male'
}
]
}
]
}
]
var childrenArr = [];
for (var i = 0; i < json.length; i++) {
var family = json[i].family;
var couples = json[i].couples;
for (var j = 0; j < couples.length; j++) {
var couple = couples[j].couple;
var childrens = couples[j].childrens;
for (var y = 0; y < childrens.length; y++) {
var children = childrens[y];
children.__proto__ = { couple : couple, family : family};
childrenArr.push(children);
}
}
}
console.log(childrenArr);
// Example of accessing family attributes or couple attributes
console.log(childrenArr[0].family.name);
P.S.: in the example above, you can access childrenArr[0].family.name