ucnumara ucnumara - 10 months ago 54
JSON Question

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

Answer Source

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
            }));
        });
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download