JavaScript: How to set a value in a multidimensional object without eval()

I’m trying to stop using eval() in JavaScript, since it is deprecated.  Today I figured out how to update a variable that is buried in a multidimensional object without using eval(). This is useful if you have an application where you have to pass object references using strings.

Here’s the method:

function setDeepValue(obj, keys, val) {
	if(typeof keys == 'string')
		keys = keys.split('.');
	var last = keys.pop(); // get the last element off.
	for(var i in keys) {
		if(!obj.hasOwnProperty(keys[i]))
			break;
		obj = obj[keys[i]]; // updating reference
	}
	if(obj.hasOwnProperty(last))
		obj[last] = val; // set the value
}

Usage:

Let’s say I have this object:

var one = {two: {three: 'four'}};

I can set a deep variable like this:

setDeepValue(one, 'two.three', 4);

This is the same as doing this:

one.two.three = 4;

This is made possible because objects are passed by reference, and primitive types (like strings or numbers) are passed by value.

Oh, here’s a jsfiddle for ya.

Leave a Reply

Your email address will not be published. Required fields are marked *