Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  4] [ 2]  / answers: 1 / hits: 155721  / 12 Years ago, wed, may 23, 2012, 12:00:00

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?


More From » jquery

 Answers
18

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.


[#85396] Tuesday, May 22, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byrondonavanc

Total Points: 675
Total Questions: 107
Total Answers: 105

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
byrondonavanc questions
;