简体   繁体   中英

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 在此处输入图片说明

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?

Try this:

JAVASCRIPT

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

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>'));
   }
});

为此,可以使用underscore.js库以数组的形式获取与特定键相对应的全部数据。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM