Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key and value of object in JavaScript?

Tags:

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?

like image 484
flossfan Avatar asked May 23 '12 10:05

flossfan


1 Answers

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:

  • An object has data and structure.
  • 'Adidas', 'Nike', 100 and 50 are data.
  • Object keys are structure. Using data as the object key is semantically wrong. Avoid it.

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.

like image 167
Tomalak Avatar answered Nov 05 '22 02:11

Tomalak