Adam Halasz
Adam Halasz

Reputation: 58301

Javascript Dynamic Arrays and Object

Is this possible?

So I need to have an array with a dynamic name and content what can be extended and accessed.

object = {};
var two = ['thing', 'thing2'];
for(one in two){
    object[two[one]] = [];
}

If yes but not in this way, then how?

Upvotes: 0

Views: 853

Answers (2)

Phrogz
Phrogz

Reputation: 303254

var object = {};
var props  = 'thing thing2'.split(' ');
for (var i=0,len=props.length;i<len;++i){
  object[props[i]] = [];
}

Upvotes: 1

Jacob Relkin
Jacob Relkin

Reputation: 163248

This is definitely doable, just make sure that the object owns the property and it's not inherited from higher up in the prototype chain:

object = {};
var two = ['thing', 'thing2'];

for..in:

for(var one in two){
    if(two.hasOwnProperty(one))
       object[two[one]] = [];
}

for:

for(var i = 0; i < two.length; i++)
   object[two[i]] = [];

Upvotes: 1

Related Questions