Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  137] [ 1]  / answers: 1 / hits: 35469  / 12 Years ago, wed, december 5, 2012, 12:00:00


Suppose we are only given



var obj = {};
var propName = foo.bar.foobar;


How can we set the property obj.foo.bar.foobar to a certain value (say hello world)?
So I want to achieve this, while we only have the property name in a string:



obj.foo.bar.foobar = hello world;

More From » string

 Answers
6
function assign(obj, prop, value) {
if (typeof prop === string)
prop = prop.split(.);

if (prop.length > 1) {
var e = prop.shift();
assign(obj[e] =
Object.prototype.toString.call(obj[e]) === [object Object]
? obj[e]
: {},
prop,
value);
} else
obj[prop[0]] = value;
}

var obj = {},
propName = foo.bar.foobar;

assign(obj, propName, Value);

[#81609] Monday, December 3, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leiaf

Total Points: 10
Total Questions: 101
Total Answers: 84

Location: Guam
Member since Tue, Nov 29, 2022
2 Years ago
;