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?
asked Nov 23, 2010 at 21:09
Adam Halasz
58.5k67 gold badges154 silver badges216 bronze badges
2 Answers 2
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]] = [];
answered Nov 23, 2010 at 21:12
Jacob Relkin
164k34 gold badges352 silver badges321 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Phrogz
You are missing a
var on one, causing it to be globally defined (and potentially collide).Jacob Relkin
@Phrogz, Oops. Missed that one. Thanks!
var object = {};
var props = 'thing thing2'.split(' ');
for (var i=0,len=props.length;i<len;++i){
object[props[i]] = [];
}
answered Nov 23, 2010 at 21:17
Phrogz
304k115 gold badges669 silver badges758 bronze badges
Comments
lang-js
Arraywithfor-inis considered bad practice; use a C-styleforloop or useArray.prototype.forEachif available.onevariable, unless you havevar oneelsewhere in your function. Best practice for iterating properties of an object isfor (var prop in obj){ if (obj.hasOwnProperty(prop)){ ... } }.