Reputation: 58810
I'm trying to access the value of a certain fields of my JSON file.
console.log( objects.assignments.header.report_type );
I want to print out HOMEWORK
$.ajax({
url: "/BIM/rest/report/assignment",
type: "POST",
dataType : "json",
data: {
assessmentId: "206a9246-ce83-412b-b8ad-6b3e28be44e3",
classroomId: "722bfadb-9774-4d59-9a47-89ac9a7a8f9a"
},
success: function( objects ) {
console.log( objects.assignments.header.report_type );
// Result : Uncaught TypeError: Cannot read property 'report_type' of undefined
{
"assignments": [
{
"assignmentId": "SUMMARY",
"name": "Summary",
"header": {
"section_num": "9.4",
"report_type": "HOMEWORK",
"problem_set": "Summary",
"start_time": null,
"student_am": 0,
"student_total": 5,
"due_time": null,
"submit_am": 0,
"submit_total": 0,
"avg_score": "0.0",
"danger": 0,
"danger_list": "",
"warning": 0,
"warning_list": "",
"success": 0,
"success_list": ""
}
}
]
}
How do I access those data properly ?
Any hints / helps on that will mean a lot to me.
Thanks in advance.
Upvotes: 2
Views: 99
Reputation: 4670
Assuming you have multiple values in your array and want to access them all:
for (var i = 0; i < objects.assignments.length; i++) {
console.log(objects.assignments[i].header.report_type);
}
Upvotes: 0
Reputation: 80
{} means you have a object that has key,value pairs
[] means it is an array that has index (position if you like), value pairs.
var myObject = {
'a_key':'A_value',
'b_key':'B_value',
'c_key':'C_value'
};
var myArray = [
'A_value',
'B_value',
'C_value'
];
To access the value of an object you use the key
console.log(myObject.a) // A_value
console.log(myObject['c']) // C_value
values in arrays are available by the index (starting from zero)
console.log(myArray[0]) // A_value
console.log(myArray[2]) // C_value
You can have an array of objects or an object containing some arrays
so in your example it would be:
console.log( objects.assignments[0].header.report_type )
^ ^ ^ ^ ^
variable key index key key
name 1st lvl 1st lvl 2nd lvl
Upvotes: 1
Reputation: 4091
assignments
is an array, so you need to access a specific element.
console.log(objects.assignments[0].header.report_type);
^^^
Upvotes: 3
Reputation: 3148
Since assignments
is an array therefor you must specify an index to access properties inside it. To access use:
objects.assignments[0].header.report_type
Upvotes: 3
Reputation: 769
$.ajax({
url: "/BIM/rest/report/assignment",
type: "POST",
dataType : "json",
data: {
assessmentId: "206a9246-ce83-412b-b8ad-6b3e28be44e3",
classroomId: "722bfadb-9774-4d59-9a47-89ac9a7a8f9a"
},
success: function( objects ) {
console.log( objects.assignments[0].header.report_type );
Upvotes: 3