2

I want to set object properties using a string selector. I have a string model.name and I have a object to store the values in. Instead of storing the value in object[model.name] I want to store it in object[model][name].

How can that be accomblished with javascript/jQuery or a javascript/jQuery plugin?

2
  • Why downvote? Ok, is a simple question. But anyone here was a noob in the past. Or not? Commented Jul 11, 2012 at 15:33
  • I tried the most of the common ways of setting data, that i know from php, i usually don't work with javascript, i normally work with back-end programming creating ORM systems... Commented Jul 11, 2012 at 15:49

1 Answer 1

3
function setObjectPathValue(source, path, value) {
    var parts = path.split('.'), len = parts.length, target = source;

    for (var i = 0, part; i < len - 1; i++) {
        part = parts[i];
        target = target[part] == undefined ? (target[part] = {}) : target[part];
    }
    target[parts[len - 1]] = value;
    return target;
}

var obj = {};
setObjectPathValue(obj, "level1.level2.level3.name", "test");
alert(obj.level1.level2.level3.name);
Sign up to request clarification or add additional context in comments.

Comments

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.