Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access JSON Nested arrays with jquery

I'm trying to access all brands and values for dropdown menu but I couldn't that with this way.

<select id="secim">
</select>

var data = [
        {
          "products": "Cars",
          "brands_values" : [
            {"brand":"fiat","value":1},
            {"brand":"bmw","value":2}
          ]
      }
      ];

$.each(data, function(i, item) {
        $('#secim').append($('<option>', {
          value: item.brands_values.value,
          text: item.brands_values.brand
        }));
      });

How could I do? Thank you

like image 247
ucnumara Avatar asked Sep 01 '25 10:09

ucnumara


1 Answers

Just add another loop for the brands:

var data = [
  {
    "products": "Cars",
    "brands_values" : [
      {"brand":"fiat","value":1},
      {"brand":"bmw","value":2}
    ]
}];

$.each(data, function(i, item) {
  if (item.brands_values) {
      item.brands_values.forEach(brands => {
        $('#secim').append($('<option>', {
          value: brands.value,
          text: brands.brand
        }));
      });
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="secim">
</select>

Note: You may want to use native .forEach in that case, since it is enough. I had performance issues with jQuery.each() in the past so I avoid it whenever I can(check this):

data.forEach(item => {
    if (item.brands_values) {
        item.brands_values.forEach(brands => {
            $('#secim').append($('<option>', {
                value: brands.value,
                text: brands.brand
            }));
        });
    }
});
like image 51
DontVoteMeDown Avatar answered Sep 04 '25 03:09

DontVoteMeDown