[javascript] Get key and value of object in JavaScript?

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?

This question is related to javascript jquery

The answer is


$.each(top_brands, function(index, el) {
  for (var key in el) {
    if (el.hasOwnProperty(key)) {
         brand_options.append($("<option />").val(key).text(key+ " "  + el[key]));
    }
  }
});

But if your data structure is var top_brands = {'Adidas': 100, 'Nike': 50};, then thing will be much more simple.

for (var key in top_brands) {
  if (top_brands.hasOwnProperty(key)) {
       brand_options.append($("<option />").val(key).text(key+ " "  + el[key]));
  }
}

Or use the jquery each:

$.each(top_brands, function(key, value) {
    brand_options.append($("<option />").val(key).text(key + " "  + value));
});

for (var i in a) {
   console.log(a[i],i)
}

$.each(top_brands, function() {
  var key = Object.keys(this)[0];
  var value = this[key];
  brand_options.append($("<option />").val(key).text(key + " "  + value));
});

If this is all the object is going to store, then best literal would be

var top_brands = {
    'Adidas' : 100,
    'Nike'   : 50
    };

Then all you need is a for...in loop.

for (var key in top_brands){
    console.log(key, top_brands[key]);
    }

Object.keys(top_brands).forEach(function(key) {
  var value = top_brands[key];
  // use "key" and "value" here...
});

Btw, note that Object.keys and forEach are not available in ancient browsers, but you should use some polyfill anyway.