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
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
}));
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With