Iterate through object (array) within returned JSON array
Iterate through object (array) within returned JSON array

Here's the returned json:
[{
"name":"2017 Dues",
"bill_yr":"2017",
"status":"inactive",
"schedules":[["sched A"],["sched B"],["sched C"],["sched D"]
]},
{
"name":"2018 Dues",
"bill_yr":"2018",
"status":"
"schedules":[["sched A"],["sched B"]
]},
Here's ajax:
$('#example').DataTable( {
processing: true,
select: true,
ajax:
{
"url": "../results.php",
"type": "post",
"data": {
"cycles": "submitted",
"key": "123"
},
"dataType": 'json',
"dataSrc": "",
},
columns:
[
{"data": 'name'},
{"data": 'bill_yr'},
{"data": 'status'},
{"data": "schedules"} ** What to do here to iterate over schedules? **
]
});
I would like to have a row like this:
2017 Dues | 2017 | inactive | sched A <br /> sched B
This question has an accepted answers - jump to answer
Answers
Use
columns.render
to loop through the array to build your string. There are some examples of transforming the data here:https://datatables.net/manual/data/renderers#Functions
Kevin
Something like this? I can't even get a console.log to print from within that function.
columns:
[
{data: 'name'},
{data: 'bill_yr'},
{data: 'status'},
{data: 'schedules',
render: function(data){
var sched = json.PARSE(data);
console.log(sched);
You are getting this error:
It should be
JSON.parse(data);
. Likely you dont need this as it is probably already a Javascript array. You could use something as simple as join(). For example:http://live.datatables.net/pabufege/1/edit
Kevin
I'm not sure what the problem is. It just won't display for me. Here's a snapshot of the data coming back to me:
Hard to say without actually seeing it. Maybe you can copy the JSON response from the developer tools and update my example with it. Or post a link to your page so we can look.
I assume you aren't seeing errors in the browser's console.
Kevin
No errors in the console. Where do you want me to paste the json response in the JS Bin?
It works here so I'm not sure what I'm missing:
live.datatables.net/jibedupu/1/edit?html,css,js,output
I figured it out
I commented "success" and it worked. Why would that be the case?
ajax:
{
"url": "../results.php",
"type": "post",
"data": {
"cycles": "
},
"dataType": 'json',
"dataSrc": "",
"success": function(data, jqXHR, textStatus) {
if (data.error) {
$('#alert_message').html("
");
}
}
},
columns:
[
{"data": 'cycle_name'},
{"data": 'bill_year'},
{"data": 'port_vis'},
{"data": 'status'},
{"data": 'schedules',
"render": function(data){
return data.join('<br/>');
}
}
]
You can start with using
console.log
to help debug. For example:Hopefully this will give you a hint of what to do next.
Kevin
This is from the
ajax
docs:Kevin