How to create 2nd level property with for JS object using bracketss

1.6k views Asked by At

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?

2

There are 2 answers

1
Mike Thomsen On

Try this:

prepObj[index_id] = {};
prepObj[index_id][which_prop] = prop_value;
6
apsillers On

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 of index_id

  • typeof prepObj[index_id] != "undefined" - this tests if the value of prepObj[index_id] is not undefined

  • prepObj[index_id] || {} - this evaluates to prepObj[index_id] if it's not a falsy value (like undefined); otherwise it evaluates to a new object