How Can I Declare A Value Deep In An Object Tree Using Variable Properties In Javascript
I am trying to have a javascript object tree behave like a php associative array in the following way. var key1 = 'a'; var key2 = 'b'; var key3 = 'c'; var obj[key1][key2][key3] =
Solution 1:
I don't know if there's a "natural" way to do it, but you could do it like this:
functionphpLike(){};
phpLike.prototype.set = function ()
{
var l = arguments.length;
if (l<2) return;
var o = this;
for (var i=0; i<l-2; i++)
{
if (o[arguments[i]] === undefined) o[arguments[i]] = {};
o = o[arguments[i]];
}
o[arguments[l-2]] = arguments[l-1];
}
// Testvar key1 = 'a';
var key2 = 'b';
var key3 = 'c';
var obj = newphpLike();
obj.set(key1, key2, key3, 'd');
alert(obj[key1][key2][key3]);
Solution 2:
functionsetPropertyByKeyPath(obj, path, val) {
var key;
while (path.length > 1) {
key = path.shift();
obj[key] = typeof obj[key] === "object" ? obj[key] : {};
obj = obj[key];
}
obj[path.shift()] = val;
}
var o = {};
setPropertyByKeyPath(o, ['foo', 'bar'], 5);
alert(o.foo.bar)
Solution 3:
Not directly, as far as I know, but how about using a little helper function?
functionkv1(k, v) {
var o = { };
o[k] = v;
return o;
}
var obj = kv1(key1, kv1(key2, kv1(key3, 'd')));
Solution 4:
I just thought of an answer inspired by Will's post: Construct a json string and then eval().
var obj = eval("{" + key1 + ": {... }};");
This kind of fulfils my search for a more concise way of declaring an object tree and deep leaf. But, it is ugly, confusing and I would avoid it like the plague.
Solution 5:
varobj= { key1: { key2: { key3:'d' } } }
This syntax is the basis of the format known as JSON: http://en.wikipedia.org/wiki/JSON
Post a Comment for "How Can I Declare A Value Deep In An Object Tree Using Variable Properties In Javascript"