0

I have json object in data after ajax call like

[
  {
    "_id": {
      "$id": "58d8e2831d7859e80d000033"
    },
    "broadcast_id": 70,
    "studentList": "",
    "employeeList": "999",
    "mailTitle": "adsf",
    "broadcastMessage": "dsfsdf dsd fgd",
    "emailSent": "0",
    "userdetails": []
  },
  {
    "_id": {
      "$id": "58d8eaba1d7859c81300002e"
    },
    "broadcast_id": 72,
    "studentList": "",
    "employeeList": "999|788",
    "mailTitle": "Hekjh",
    "broadcastMessage": "hhyky jk",
    "emailSent": "0",
    "userdetails": []
  },
  {
    "_id": {
      "$id": "58dde8ed1d78597011000029"
    },
    "user_id": 1,
    "broadcast_id": 76,
    "studentList": "",
    "employeeList": "999|788",
    "mailTitle": "Hello",
    "broadcastMessage": "How are u ",
    "emailSent": "0",
    "dateSent": "31/03/2017",
    "userdetails": [
      {
        "_id": {
          "$id": "568f95dc99fbadb016000029"
        },
        "uid": 1,
        "username": "test",
        "password": "LeLafe#7861",
        "email_id": "[email protected]",
        "creation_date": "",
        "role": "admin",
        "is_enabled": 1
      }
    ]
  }
]

Now I am trying parse nested json attribute userdetails in order to role and display it in a table. I have tried following lines

 $.ajax({
         url: 'index.php?action=fetchBroadcastedMessageList',
         type: 'POST',
         dataType: 'JSON',
         data: { usertype: usertype },
         success: function(data) {
             for (var i in data) {
                 $("#broadcastedmessagelist").append('<tr>' +
                     '<td style="text-align: center;">' +
                     '' + data[i].userdetails["role"] + '' +
                     '</td>'...
                 );
             }
         });
 }

The line data[i].userdetails["role"] does not retrieve corresponding role value whereever there are userdetails available. Please help me !!!

3
  • The userdetails is contains an array, you have to use data[i].userdetails[0]["role"] in order to do what you want to Commented Apr 6, 2017 at 7:07
  • data[i].userdetails is an array Commented Apr 6, 2017 at 7:09
  • did you check my answer ? Commented Apr 9, 2017 at 8:29

8 Answers 8

2

You can also use like this

 $.ajax({
       url: 'index.php?action=fetchBroadcastedMessageList',
       type: 'POST',
       dataType: 'JSON',
       data: {usertype: usertype},
       success: function (data) {
            $.each(data , function(key,value)) {
                       $("#broadcastedmessagelist").append('<tr>' +
                              '<td style="text-align: center;">' +
                              '' + value.userdetails[0]["role"] + '' +
                              '</td>'...
           );
           }
       });  
      }
Sign up to request clarification or add additional context in comments.

Comments

2

You need an additional level ([0]), since userdetails returns an array. For this to work you must first check if the array has elements:

   $("#broadcastedmessagelist").append('<tr>' +
      '<td style="text-align: center;">' +
          (data[i].userdetails.length ? data[i].userdetails[0]["role"] : '') +
      '</td>'
   );

Maybe you want the check on the array length to happen earlier, so that you can omit the append completely when the array has no elements. Depends on what you expect...

if (data[i].userdetails.length) {
   $("#broadcastedmessagelist").append('<tr>' +
      '<td style="text-align: center;">' +
          data[i].userdetails[0]["role"] +
      '</td>'
   );
}

3 Comments

Solution looks good but what if userdetails is a string, it will also have a length property. In that case userdetails[0] can give awkward results
Sure, it would also give awkward results if it was a date, a boolean, null, ... But OP's sample data suggests that it always is an array. I assume of course there is a consistent structure in the received JSON.
This can be done just to be sure "Array.isArray(userdetails)" before checking the length property.
1

rather use forEach and then just use that object. It seems that is what you are trying to achieve anyway.

$.ajax({
                    url: 'index.php?action=fetchBroadcastedMessageList',
                    type: 'POST',
                    dataType: 'JSON',
                    data: {usertype: usertype},
                    success: function (data) {
                 data.forEach(function(obj) {
                  $("#broadcastedmessagelist").append('<tr>' +
                   '<td style="text-align: center;">' +
                   '' + obj.userdetails.role + '' +
                   '</td>'...
           );
       });
       });  
      }

1 Comment

Sorry, this is the case if userdetails is not an array, I am not sure why you want to make it an array? Otherwise trincot has a nice answer
1

It should be

data.userdetails[0].role

Comments

0

var data= [{"_id":{"$id":"58d8e2831d7859e80d000033"},"broadcast_id":70,"studentList":"","employeeList":"999","mailTitle":"adsf","broadcastMessage":"dsfsdf dsd fgd","emailSent":"0",
            "userdetails":[]},
     {"_id":{"$id":"58d8eaba1d7859c81300002e"},"broadcast_id":72,"studentList":"","employeeList":"999|788","mailTitle":"Hekjh","broadcastMessage":"hhyky jk","emailSent":"0",
          "userdetails":[]},
     {"_id":{"$id":"58dde8ed1d78597011000029"},"user_id":1,"broadcast_id":76,"studentList":"","employeeList":"999|788","mailTitle":"Hello","broadcastMessage":"How are u ","emailSent":"0","dateSent":"31\/03\/2017",
           "userdetails":[{"_id":{"$id":"568f95dc99fbadb016000029"},"uid":1,"username":"test","password":"LeLafe#7861","email_id":"[email protected]","creation_date":"",
           "role":"admin",
           "is_enabled":1}]}]
           
           $.each(data,function(i,item){
           if(item.userdetails.length > 0)
           {
           $.each(item.userdetails,function(i,userdetail){
           $("#broadcastedmessagelist").append('<tr>' +'<td style="text-align: center;">' +userdetail.role +'</td>');
           });
           }
           else
           {
           $("#broadcastedmessagelist").append('<tr>' +'<td style="text-align: center;">' +'not available' +'</td>');
           }
           });
           
          
           
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="broadcastedmessagelist">

</table>

Comments

0

As stated above you need an extra level nesting. Also suggest using the es6 template strings for a cleaner string interpolation.

data.map((i)=>{
  if(i.userdetails.length >0){
    $("#broadcastedmessagelist")
    .append(`<tr><td style="text-align:center;">${i.userdetails[0].role}</td>`);
  } 
})

Comments

0

Observation : userdetails is an array so to access any element from an array you have to use like this : data[i].userdetails[0]["role"]

try this :

for (var i in data) {
                 $("#broadcastedmessagelist").append('<tr>' +
                     '<td style="text-align: center;">' +
                     '' + data[i].userdetails[0]["role"] + '' +
                     '</td>'...
                 );
             }

Comments

-1

/* below code will call to index.php, catch the json response and render HTML */

$.ajax({
  url: 'index.php?action=fetchBroadcastedMessageList',
  type: 'POST',
  dataType: 'JSON',
  data: {usertype: usertype},
  success: function (data) {
 $("#broadcastedmessagelist").append('<tr><td>broadcastMessage</td><td>broadcast_id</td><td>emailSent</td><td>employeeList</td><td>mailTitle</td><td>studentList</td><td>userdetails</td></tr>');
    $.each(data, function(key,value){
      var stringBuilder = '<tr><td>' + value.broadcastMessage + '</td><td>' + value.broadcast_id + '</td><td>' + value.emailSent + '</td><td>' + value.employeeList + '</td><td>' + value.mailTitle + '</td><td>' + value.studentList + '</td>';

      if(value.userdetails.length > 0){
        stringBuilder = stringBuilder + '<td><table border="1"><tr><td>uid</td><td>username</td><td>password</td><td>email_id</td><td>creation_date</td><td>is_enabled</td><td>role</td></tr>';
        $.each(value.userdetails, function(k,v){
          stringBuilder =  stringBuilder + '<tr><td>' + v.uid + '</td><td>' + v.username + '</td><td>' + v.password + '</td><td>' + v.email_id + '</td><td>' + v.creation_date + '</td><td>' + v.is_enabled + '</td><td>' + v.role + '</td></tr>';
        });
        stringBuilder =  stringBuilder + '</table></td>';
      }else{
        stringBuilder =  stringBuilder + '<td></td>';
      }
      stringBuilder =  stringBuilder + '</tr>';
      $("#broadcastedmessagelist").append(stringBuilder);
    });
     }
});

1 Comment

Code-only answers are discouraged at SO. Please, explain in words, what was wrong and how you suggest to fix that.

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.