0

I would like to have a for loop create objects as the children of a parent object. Usually, I would declare the object without using the for loop like this:

 var mObj = {};
 mObj.obj1 = {};
 mObj.obj2 = {};
 mObj.obj3 = {};
 mObj.obj3.firstname = "john";
 mObj.obj3.lastname = "superfly";

Now lets say I would like to employ a for loop to create the children objects of a parent object "mObj".

This is where I am going wrong:

var mArr = ["firstname","lastname","email"]; // This array holds the keys for the   objects

 var mObj = {};

 var len = (mArr.length);

 for(var i=0; i<len; i++){

      var obj+i = {}
      mObj = obj+i;
      mObj.obj + i.mArr[i] = ""

    }

So the outcome of this would be:

 mObj.obj1.firstname = "";
 mObj.obj2.lastname = "";
 mObj.obj3.email = "";

I just cannot seem to name the object with counter that is being created within for loop like:

obj1
obj2
obj3

Any help would highly be appreciated.

Thanks.

3 Answers 3

1

var obj+i = {} is invalid syntax.

Try this:

mObj['obj' + i] = {};

If i == 1, this gives mObj['obj1'] = {};

Which is equiavlent to:

mObj.obj1

But when constructing dynamically, you have to use the

mObj['obj' + i]

Formatting.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot. After some elbow grease, I got it going. I spend hours trying things out that darn . syntax was throwing me off.
1
var mArr = ["firstname","lastname","email"],
    mObj = {},
    len  = (mArr.length),
    i    = 0;

 for(; i<len; i++){
      myObj['obj' + i] = {}
      myObj['obj' + i].mArr[i] = ""
  }

Comments

0

You need to use the bracket syntax to assign a dynamic variable. For example:

var sampleObj = {};

for(var j = 0; j < 3; j++)
{
    sampleObj["obj" + j] = { test: j };
}

This should produce the following object:

{
    "obj1" : { test: 1 },
    "obj2" : { test: 2 },
    "obj3" : { test: 3 }
}

After running the loop then, you could validly use this statement:

var testVal = sampleObj.obj1.test;

1 Comment

var keyArr = ["firstname","lastname","email"] var valArr = ["John","Superfly","[email protected]"]; mObj = {}, len = (mArr.length), i = 0; for(; i<len; i++) { mObj['obj' + i] = {}; mObj['obj' + i][mArr[i]] = valArr[i]; } console.log(mObj.obj2.email);

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.