Reputation: 581
Can someone explain to me how to make a json that contains a nested an array within an array?
Assuming I have two tables, the first is "group" and the second "students", and I want to make a json like this:
[
group: "X"
{
{
id: "1",
name: "Student z",
},
{
id: "2",
name: "Student b",
}
},
group: "N"
{
{
id: "3",
name: "Student c",
},
{
id: "4",
name: "Student a",
}
} ]
I've always done simple json, where it is not grouped at all, but this time it is different.
In addition, groups are dynamic, they are not defined and may change over time.
I know it's a silly question, but I would like someone to help me, please.
Upvotes: 0
Views: 2706
Reputation: 8174
Let's start with an object structure where the group name are the keys, like this:
{X: details-about-X, N: details-about-N}
For each group, we want a list of students - so each group needs to contain an array:
{
X: [item1, item2],
N: [item1, item2]
}
or written another way,
{
X: [
item1,
item2
],
N: [
item1,
item2
]
}
And each item in the array is a student with a name and an id - so a student object:
{
id: 1,
name: "Student z"
}
Plugging that into the original structure as the array items, we get this:
{
X: [
{
id: 1,
name: "Student z"
},
{
id: 2,
name: "Student b"
}
],
N: [
{
id: 3,
name: "Student c"
},
{
id: 4,
name: "Student a"
}
]
}
If this structure is saved to a javascript variable groups
, you'd be able to access the list of students in group N as:
groups.N
..the details about the first student in group N as:
groups.N[0]
...and the name of the first student in group N as:
groups.N[0].name
An alternative would be to start with an array of groups, and build a structure something like this:
groups = [
{
group: 'X',
students: [list-of-students, same-as-above]
}
{
group: 'N',
students: [list-of-students, same-as-above]
}
];
In that case, you could find the name of your first group with:
groups[0].name
And the name of the first student in the first group with:
groups[0].students[0].name
Upvotes: 2
Reputation: 2841
I'm not sure what is the question, but an object like that would be this:
{
X : [
{
id: "1",
name: "Student z",
},
{
id: "2",
name: "Student b",
}
], N : [
{
id: "3",
name: "Student c",
},
{
id: "4",
name: "Student a",
}
]
}
Is that what you wanted?
Upvotes: 0