Reputation: 733
I have a JSON structure for images and every image has some tags in this JSON. The structure is like that:
{
"data":[
{
"title":"Image Title",
"slug":"image-title",
"file_name":"f57fd83c-3c46-4f5b-95b8-446cca3664b5.jpg",
"added_at":"2015-09-24",
"tags":{
"data":[
{
"name":"Some Dummy Tag Name",
"slug":"some-dummy-tag-name"
},
...
]
},
"added_by":{
"data":{
"email":"[email protected]",
"first_name":"John",
"last_name":"Appleseed"
}
}
},
...
]
}
And I'm trying to show this JSON data in DataTables. I've managed to render all of the data except tags. I've used the below code for DataTables options but I can't get the tag's name. It returns [object Object] for each tag in each image. But when I try logging the "data[key].name" on the console, it successfully returns the name. What I'm doing wrong?
'columnDefs': [
...,
{
'targets': 2,
'data': 'tags.data',
'render': function(data) {
return $.each(data, function(key) {
return data[key].name;
});
}
},
...
],
Thanks in advance.
Upvotes: 1
Views: 1027
Reputation: 58860
$.each()
returns its first argument, the object that was iterated.
Use $.map()
to produce an array of tags and join(', ')
to produce a comma-separated tag list as a string from the array.
'render': function(data, type, row) {
var tags = $.map(data, function(tag, i) {
return tag.slug;
});
return tags.join(', ');
}
Upvotes: 4