I am using ajax to make a call to the server and get back some user data. The server returns back an array formatted like below:
array:6 [▼
0 => array:17 [▼
"id" => 334
"provider" => "some_provider"
"option_id" => "x124223"
"option_title" => "title"
"api_parameter" => "parameter"
"chart_title" => "title"
"chart_color" => "#6a76fc"
"chart_target" => "2220"
"chart_type" => "line"
"chart_size" => "4"
"chart_data" => array:7 [▼
239 => array:2 [▼
"data" => 2114
"created_at" => "14/August"
]
240 => array:2 [▼
"data" => 2114
"created_at" => "15/August"
]
241 => array:2 [▶]
242 => array:2 [▶]
243 => array:2 [▶]
244 => array:2 [▶]
245 => array:2 [▶]
]
"average" => 2122.0
"current" => array:2 [▶]
"last" => array:2 [▶]
"current_status_icon" => "md-trending-neutral"
"current_status_color" => "#3DDCF7"
"status_message" => "hmm... The needle didnt move."
]
1 => array:17 [▼
"id" => 345
"provider" => "some_other_provider"
"option_id" => "x124"
"option_title" => "Title"
"api_parameter" => "parameter"
"chart_title" => "title"
"chart_color" => "#6A76FC"
"chart_target" => "Set a target"
"chart_type" => "line"
"chart_size" => "4"
"chart_data" => array:7 [▼
202 => array:2 [▼
"data" => 5
"created_at" => "13/August"
]
203 => array:2 [▼
"data" => 5
"created_at" => "14/August"
]
204 => array:2 [▶]
205 => array:2 [▶]
206 => array:2 [▶]
207 => array:2 [▶]
208 => array:2 [▶]
]
"average" => 5.0
"current" => array:2 [▼
"data" => 5
"created_at" => "16/August"
]
"last" => array:2 [▼
"data" => 5
"created_at" => "16/August"
]
"current_status_icon" => "md-trending-neutral"
"current_status_color" => "#3DDCF7"
"status_message" => "hmm... The needle didnt move."
]
I then try to access the data within the array using a foreach loop
$.ajax({url: "/url/to/server", success: function(result){
result.forEach(function(item) {
console.log(item['chart_data']['data']);
});
}, complete: function() {
// Schedule the next request when the current one's complete
setTimeout(checkForUpdates, 3000);
}
});
});
But this just logs undefined. How do I access the chart_data nested within each of the top level arrays?
chart_datais an array, which has elements that have thedataproperty. So you'll need another nested loopUncaught TypeError: item.chart_data.forEach is not a functionconsole.log(JSON.stringify(result)). That way we will see the correct JSON.