0

How can I refer to an object element dynamically during a loop by using an array, something like this:

var obj = {};
var lvl = ['x','y','z'];
var ol = [];
for (var l in lvl){
    ol.push( lvl[l] )
    obj[ol] = 'someval'
}

so where the reference may be obj[x][y][z] so each time the loop iterates, an additional key reference is appended, but I do not know how many levels there will be.

Not sure if I have explained that very well ?!

5
  • are you sure you want this? obj[ol] this will keep an array as key of object. or do you want obj[ol[l]]. Commented Jan 7, 2015 at 4:40
  • I am looking to dynamically add [] each time the loop iterates, so at the end of this example the refernce would be obj[x][y][z]. Commented Jan 7, 2015 at 4:42
  • Ok so just to be clear you want obj[x][y][z] = "someval". Essentially nesting object keys? Commented Jan 7, 2015 at 4:46
  • yes, I am looping through an array and I need to be able to push to or add key-value pairs to a nested object Commented Jan 7, 2015 at 4:48
  • did any of the answers match what you were looking for? Commented Jan 7, 2015 at 6:55

2 Answers 2

1

Based on how you answered my comment I believe this code will provide the nested object structure you are looking for.

var obj = {};
var lvl = ['x','y','z'];
var ol = {};

for (var i = 0; i < lvl.length; i++){
  obj[i] = {};  
  ol = obj[key];
}
Sign up to request clarification or add additional context in comments.

2 Comments

the var key in lvl bit is wrong because it would give you 0,1,2,length not x,y,z. Found out the hard way when testing my own answer. Use foreach or a regular for(x=0;x<lvl.length;x++) loop.
Alternatively, you can change lvl to be {x:'',y:'',z:''} instead of an array.
0

You mean you want someval to be the value of obj.x.y.z? You can always refer to the newly created levels using a variable:

var obj = {};
var levels = ['x','y','z'];

var pointer = obj;

for (var l=0; l<levels.length; l++) {
    key = levels[l];

    if (l < levels.length-1) {   // if not last element
        pointer[key] = {};
        pointer = pointer[key];
    }
    else {                       // if last element
        pointer[key] = 'someval';
    }
}

console.log(obj); // should log {x:{y:{z:"someval"}}}

1 Comment

OK. Finally got it working. Remember, variables are references only when they're pointing to arrays or objects. But they're values once you assign a string or number to them.. arrrrgh...

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.