0

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?

3
  • 2
    Eh? I'm not sure what you're asking. Also, iterating an Array with for-in is considered bad practice; use a C-style for loop or use Array.prototype.forEach if available. Commented Nov 23, 2010 at 21:11
  • Sorry, it's really hard to explain for me :\ Commented Nov 23, 2010 at 21:13
  • Note that the code sample you show there declares a global one variable, unless you have var one elsewhere in your function. Best practice for iterating properties of an object is for (var prop in obj){ if (obj.hasOwnProperty(prop)){ ... } }. Commented Nov 23, 2010 at 21:15

2 Answers 2

1

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]] = [];
Sign up to request clarification or add additional context in comments.

2 Comments

You are missing a var on one, causing it to be globally defined (and potentially collide).
@Phrogz, Oops. Missed that one. Thanks!
1
var object = {};
var props  = 'thing thing2'.split(' ');
for (var i=0,len=props.length;i<len;++i){
  object[props[i]] = [];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.