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
asked Feb 27, 2013 at 17:34
chuckieDub
1,8479 gold badges30 silver badges47 bronze badges
1 Answer 1
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
};
answered Feb 27, 2013 at 17:39
Bergi
671k162 gold badges1k silver badges1.5k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
nutrients["name"]is undefined when you want to assign val.. you can just tonutrients["name"] = tds[1].innerHTMLand should work