在JavaScript中获取对象的关键和价值? [英] Get key and value of object in JavaScript?
问题描述
给定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));
});
那么,我怎样才能获得 this.key
和 this.value
对于数组中的每个条目?
So, how can I get this.key
and this.value
for each entry in the array?
推荐答案
更改您的对象。
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)
);
});
根据经验:
- 一个对象有数据和结构。
-
'阿迪达斯'
,'Nike'
,100
和50
是数据。 - 对象键是结构。使用数据作为对象键在语义上是错误的。避免它。
- An object has data and structure.
'Adidas'
,'Nike'
,100
and50
are data.- Object keys are structure. Using data as the object key is semantically wrong. Avoid it.
{Nike:50}
中没有语义。什么是耐克?什么是50?
There are no semantics in {Nike: 50}
. What's "Nike"? What's 50?
{key:'Nike',价值: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.
更好的是 {供应商:'Nike',itemsSold:50}
,因为现在值不仅在可预测的位置,它们也有有意义的名称。从技术上讲,这与上面的内容相同,但现在一个人也会理解这些值应该是什么意思。
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.
这篇关于在JavaScript中获取对象的关键和价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!