Thursday, April 19, 2012

Creating dynamic objects to a parent object and assigning keys and values?

I am almost there with this but cannot seem to get this functionality going as planned.



I have two arrays: keyArray and ValArray;



What I am trying to do is to have a function pass two arguments (keyArr,valArr). Within this function, a parent object is declared and a (for-loop) loops through the passed argument's length (in this case "keyArr") creates new objects according the length of the passed argument. And then, the newly created objects are assigned the keys and values.



The issue is that I am able to create the parent object"mObj", and children Objects to "mObj", but am only able to assgin keys and values to the first child object "obj0" not rest of the children objects correctly. At the end of the code, this is what I would like to get:



enter code heremObj.obj0.firstname = John;
mObj.obj0.lastname = superfly;
mObj.obj0.email = "john.superfly@yahoo.com";

mObj.obj1.firstname = John;
mObj.obj1.lastname = superfly;
mObj.obj1.email = "john.superfly@yahoo.com";

mObj.obj2.firstname = John;
mObj.obj2.lastname = superfly;
mObj.obj2.email = "john.superfly@yahoo.com";


This is my code:



 var keyArr = ["firstname","lastname","email"];
var valArr = ["John","Superfly","jsuperfly@yahoo.com"];

function test(keys,vals) // FUNCTION TEST ACCEPTS TWO ARGS
{
var mObj = {}; // PARENT OBJECT
var len = (keys.length); //ARGUMENT KEY'S LENGTH

for(var i=0; i<len; i++)
{
mObj["obj" + i] = {}; //CHILDREN OBJECTS ARE CREATED TO PARENT "mObj" OBJECT
mObj["obj" + i][keys[i]] = vals[i]; //KEYS AND VALUES ARE ASSIGNED HERE
}

alert(mObj.obj1.firstname); // CURRENTLY RETURNS "UNDEFINED"
}

test(keyArr,valArr);


Any insight into this would highly be appreciated.
Thank you.





No comments:

Post a Comment