简体   繁体   English

遍历javascript对象,以便将关键变量用作调用对象的方法

[英]Iterate over javascript object such that key variables are used as methods to call the object

Right now I'm hard-coding new properties into my javascript application and its a horrible code smell but I just don't know any better when it comes to javascript implementation. 现在,我正在将新属性硬编码到我的javascript应用程序中,并且它具有可怕的代码味道,但是我只是不了解javascript实现。 This is what my code looks like now: 这是我的代码现在的样子:

$.getJSON(url, function(data) {
  $("#total_population_2013").html(data.table.total_population_2013);
  $("#median_age_2013").html(data.table.median_age_2013);
  //ETCETERA, FOR A VERY LONG TIME I MIGHT ADD
});

Its a ruby OpenStruct object converted into json that I'm sending to the getJSON method. 它是一个红宝石OpenStruct对象,已将其转换为我要发送到getJSON方法的json。 Trial and error solution, but I can access its properties as shown above. 反复试验的解决方案,但是我可以如上所述访问其属性。

I'm about to add many more variables that I'll be writing into html id tags, and would prefer to do this is a more professional manner. 我将添加更多要写入html id标签的变量,并且希望以更专业的方式进行操作。 Here is what I've tried so far but is not working: 这是我到目前为止已经尝试过但无法正常工作的内容:

$.getJSON(url, function(data) {
  for(var k in data) {
    var value = data[k];
    var id_str = "#"+k;
    $(id_str).html(value);
  });
}

Thanks 谢谢

I notice two things. 我注意到两件事。 One is that for..in iterates over all properties of an object, which can include stuff that it gets from the prototype chain. 一种是for..in迭代对象的所有属性,其中可以包括从原型链获得的东西。 This is typically not what you want, so you want to do this instead: 通常这不是您想要的,所以您想这样做:

for(var k in data) if (data.hasOwnProperty(k)) {

   ...

}

This makes sure you only get the object's own properties. 这样可以确保您仅获得对象自己的属性。

Second, your JSON seems to have its data under data.table and instead you're pulling stuff just out of data . 其次,您的JSON似乎在data.table下有其数据,相反,您只是从data提取内容。 This means, you'll just get table as a value and you probably don't have anything with the id #table . 这意味着,您将只获得table作为值,并且ID #table可能没有任何#table I suspect you want: 我怀疑您想要:

for(var name in data.table) if (data.table.hasOwnProperty(k)) {
    $("#" + name).html(data.table[name]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM