dynamic object properties javascript

2019-09-20 02:31发布

Having issues with this code block:

var name = "";
var nutrients = {};
var tds = document.getElementById('data').getElementsByTagName('td');

name = tds[0].innerHTML;
nutrients[name].val = tds[1].innerHTML;
alert(nutrients.Energy.val);

If I take out the .val on both lines, the code works. I'm trying to dynamically create the " nutrients" abject by extracting information from a table. "Energy", and all 50 of nutrient names must have a "value" and a "unit" property. Eventually this will be a loop.

Thanks for any help

1条回答
祖国的老花朵
2楼-- · 2019-09-20 03:36

When trying to assign

nutrients[name].val = tds[1].innerHTML;

the nutrients object is still empty, and nutrients["Energy"] (or whatever) will be undefined; throwing an exception when beeing assigned a property. Instead, use

nutrients[name] = {
    val: tds[1].innerHTML
};
查看更多
登录 后发表回答