简体   繁体   中英

Dynamically add elements to object literal

I'm trying to dynamically create an object literal dynamically. So I start with an empty object:

   var myobj = {}

and then add entries to it so it ends up looking like so:

var myobj = {
    row1 = {
        thing1 : 'thing',
        thing2 : 'thing'
    },
   row2 = {
        thing1 : 'thing',
        thing2 : 'thing'
    }
}

I've been trying to do:

for(var i = 0; i<rows.length; ++i) {
    myobj.row[count].thing1 = 'thing';
    myobj.row[count].thing2 = 'thing'
}

But this does not seem to work. I get a cannot set property of undefined error.

Any ideas how I can do this?

You have to give myobj.row a value (and one that can accept properties, such as an array or an object) before you can give myobj.row[count] a value (and myobj.row[count] has to have a value before myobj.row[count].thing1 or myobj.row[count].thing2 can be assigned).

var myobj = { row: [] };
for(var i = 0; i<rows.length; ++i) {
    var count = i;
    myobj.row[count] = {};
    myobj.row[count].thing1 = 'thing';
    myobj.row[count].thing2 = 'thing';
}

Also, if you want to create a property called row1 then you have to use ["row" + 1] not .row.1 )

var myobj = {};
for(var i = 0; i<rows.length; ++i) {
    var count = i;
    myobj['row' + count] = {};
    myobj['row' + count].thing1 = 'thing';
    myobj['row' + count].thing2 = 'thing';
}

You are treaying row as an array, when it is strings. To use a dynamic string, you need to put the string "row" inside the brackets.

myobj.row[count].thing1 = 'thing';
myobj.row[count].thing2 = 'thing'

should be

myobj["row" + count].thing1 = 'thing';
myobj["row" + count].thing2 = 'thing'

but if you are treating it as an "array". Why don't you use an array?

var myobj = {
    rows : [ 
        {
            thing1 : 'thing',
            thing2 : 'thing'
        },
        {
            thing1 : 'thing',
            thing2 : 'thing'
        }
    ]
}

and than what you did would have worked.

myobj.rows[count].thing1 = 'thing';
myobj.rows[count].thing2 = 'thing

"row" is not an array, it is an object (because you have {} around it)

You should use:

myobj.row1.thing1 = 'thing'

If you want to use arrays, they your object should be:

var myobj = {
row : [{
        thing1 : 'thing',
        thing2 : 'thing'
    },
   {
        thing1 : 'thing',
        thing2 : 'thing'
    }]
}

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM