问题
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?
回答1:
JavaScript does not support autovivication. You must define prepObj[index_id] = {}
before you define prepObj[index_id][which_prop] = prop_value
.
This is because prepObj[index_id]
is initially not defined. Thus, you are trying to set the prop1
property on prepObj[index_id]
which is undefined
. You avoid this by making prepObj[index_id]
some defined value.
If you're worried about clobbering prepObj[index_id]
with a new object each time, you can test that the value is already set by either:
index_id in prepObj
- this tests that prepObj already has an entry whose key is the value ofindex_id
typeof prepObj[index_id] != "undefined"
- this tests if the value ofprepObj[index_id]
is notundefined
prepObj[index_id] || {}
- this evaluates toprepObj[index_id]
if it's not a falsy value (likeundefined
); otherwise it evaluates to a new object
回答2:
Try this:
prepObj[index_id] = {};
prepObj[index_id][which_prop] = prop_value;
来源:https://stackoverflow.com/questions/20380504/how-to-create-2nd-level-property-with-for-js-object-using-bracketss