I am trying to get certain classes based off their id
from the database on the server side. The data sent from the server is in JSON format. The following is the JSON I am currently working with:
var classes = {
"success": true,
"data": [
{
"id": 1,
"name": "mechanics",
"created_at": "2016-08-08T15:37:14"
},
{
"id": 2,
"name": "mechanics",
"created_at": "2011-10-02T23:25:42"
},
{
"id": 4,
"name": "Stephen's Rad New Course",
"created_at": "2016-09-07T15:44:50"
},
{
"id": 5,
"name": "English",
"created_at": "2016-10-28T07:09:45"
},
{
"id": 6,
"name": "Mathematics",
"created_at": "2017-02-15T13:33:49"
}
]
}
The id
that I am using is taken from another JSON:
var student = {
"success": true,
"data": {
"privileges": [
{
"type": "mac"
},
{
"type": "scones"
}
],
"fname": "Luke",
"loaned": [],
"classes": [
{
"name": "Stephen's Rad New Course",
"id": 4,
"created_at": "2016-09-07T15:44:50"
},
{
"name": "Mathematics",
"id": 6,
"created_at": "2017-02-15T13:33:49"
}
],
"type": "student",
"created_at": "2016-08-24T09:35:26",
"lname": "Skywalker",
"id": 44,
"email": "skywalker.ftw@cedarhouse.co.za"
}
}
Here is the code I am using to filter the data:
for (var j = 0; j < student.data.classes.length; j++) {
var class_id = student.data.classes[j].id;
classes = $.grep(classes, function(n, i) {
return n.id == class_id;
});
}
console.log(JSON.stringify(classes));
Based off the classes that that goes with the student JSON data, only those two classes with IDs of 4 and 6 should be displayed but right now nothing is being displayed.