1

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.

1 Answer 1

4

CAUSE

$.each() returns its first argument, the object that was iterated.

SOLUTION

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(', ');
}
Sign up to request clarification or add additional context in comments.

4 Comments

It totally makes sense! Thanks!
But what if i don't want comma separated , Instead i need each one to be new row .
@HosMercury, you can do return tags.join('<br>'); instead.
@HosMercury, then see child rows example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.