Given a JavaScript array of objects, how can I get the key and value of each object?
The code below shows what I'd like to do, but obviously doesn't work:
var top_brands = [ { 'Adidas' : 100 }, { 'Nike' : 50 }];
var brand_options = $("#top-brands");
$.each(top_brands, function() {
brand_options.append($("<option />").val(this.key).text(this.key + " " + this.value));
});
So, how can I get this.key
and this.value
for each entry in the array?
Change your object.
var top_brands = [
{ key: 'Adidas', value: 100 },
{ key: 'Nike', value: 50 }
];
var $brand_options = $("#top-brands");
$.each(top_brands, function(brand) {
$brand_options.append(
$("<option />").val(brand.key).text(brand.key + " " + brand.value)
);
});
As a rule of thumb:
'Adidas'
, 'Nike'
, 100
and 50
are data.There are no semantics in {Nike: 50}
. What's "Nike"? What's 50?
{key: 'Nike', value: 50}
is a little better, since now you can iterate an array of these objects and values are at predictable places. This makes it easy to write code that handles them.
Better still would be {vendor: 'Nike', itemsSold: 50}
, because now values are not only at predictable places, they also have meaningful names. Technically that's the same thing as above, but now a person would also understand what the values are supposed to mean.
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