Here's deal. I'm starting with an object literal.
var prepObj = {};
Then I will be doing a foreach where I'll be adding properties to this object. Basically, in the end it will look something like this (on a larger scale).
{
34 : {
prop1: myvalue,
prop2: myvalue,
}
87 : {
prop1: myvalue,
prop2: myvalue,
}
102 : {
prop1: myvalue,
prop2: myvalue,
}
}
Throughout the loop I'll be finding a value for a certain property of a certain index (such as prop1 of 87), and creating it for the object.
So, before the loop I'm starting with a blank object.
Then during the loop, I thought I could do:
var index_id = 87;
var which_prop = "prop1";
var prop_value = "This is a value.";
prepObj[index_id][which_prop] = prop_value;
but when I try this I get an error saying:
Uncaught TypeError: Cannot set property 'prop1' of undefined
What am I doing wrong?
Try this: