BourneShady
BourneShady

Reputation: 935

Access data from Object in json response

My json returns below shown set of array of objects and I need to access the data inside it. In the console this is what the response looks like enter image description here

What i am trying to do is to access the object to get the subcategoryid and subcategoryname then display it inside a dropdown list. Here is my code for it

$.get('ajax-subcat?cat_id=' + cat_id, function(data)
          {
              console.log(data);

              $('#subcategory').empty();

              $.each(data, function(index, subcatObj)
              {
                alert(subcatObj);
                $('#subcategory').append('<option value="' + subcatObj.Object.subcategoryid +'">' + subcatObj.subcategoryname +'</option>');
              });

          });

The thing I don't know is how to access the data inside the object. Any ideas?

Upvotes: 0

Views: 1045

Answers (3)

yugantar kumar
yugantar kumar

Reputation: 2052

For this purpose, you can use underscore.js library to get whole data corresponding to particular key in the form of array.

_.pluck(data, 'subCategoryid') // array of all values corresponding to 'subcategoryid'

Upvotes: 1

kapantzak
kapantzak

Reputation: 11750

Assuming that you have a select element in markup:

<select id="mySelectElement"></select>

Try this to iterate the object and fill the combo box:

$.get('ajax-subcat?cat_id=' + cat_id, function(data) {
   // Get a reference to the target element
   var selectTarget = $('#mySelectElement');
   // Iterate over the response data
   for (var i in data) {
      // For every object in array, append a new option element
      selectTarget.append($('<option value="' + data[i].subcategoryid + '">' + data[i].subcategoryname + '</option>'));
   }
});

Upvotes: 1

Erick Boshoff
Erick Boshoff

Reputation: 1583

Try this:

JAVASCRIPT

for (var i = 0; i < data.length; i++) {
    console.log(data[i].subcategoryid);
}

Upvotes: 2

Related Questions