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

廉价感情. 提交于 2020-01-24 01:39:06

问题


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




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!