2

Is there an easy way to extend a JavaScript object by passing a string and a value?

Basically I need something like this:

myObject = {}

var extendObj = function(obj, path, value){
}

var path = "a.b.c", value = "ciao";
extendObj(myObject, path, value);


console.log(myObject.a.b.c) //will print "ciao"
5
  • But then what will be a and b Commented Apr 24, 2013 at 1:59
  • If they are undefined an empty object. If they are defined extend it. Commented Apr 24, 2013 at 2:03
  • 1
    It IS ambiguous, but I am guessing the assumption would be - if it does not exist already, create it as an object. I think the real ambiguity here lies in this: what should it do if b already exists, but is a number and therefore cannot have a string as member. Commented Apr 24, 2013 at 2:04
  • 1
    @Chris "what should it do if b already exists, but is a number and therefore cannot have a string as member" this case will not appen Commented Apr 24, 2013 at 2:09

1 Answer 1

3
myObject = {};

var extendObj = function (obj, path, value) {
    var levels = path.split("."),
        i = 0;

    function createLevel(child) {
        var name = levels[i++];
        if(typeof child[name] !== "undefined" && child[name] !== null) {
            if(typeof child[name] !== "object" && typeof child[name] !== "function") {
                console.warn("Rewriting " + name);
                child[name] = {};
            }
        } else {
            child[name] = {};
        }
        if(i == levels.length) {
            child[name] = value;
        } else {
            createLevel(child[name]);
        }
    }
    createLevel(obj);
    return obj;
}

var path = "a.b.c",
    value = "ciao";
extendObj(myObject, path, value);


console.log(myObject.a.b.c) //will print "ciao"

http://jsfiddle.net/DerekL/AKB4Q/

enter image description here

You can see in the console that it creates the path according to path you entered.

Sign up to request clarification or add additional context in comments.

2 Comments

@MarcoCalì - I have tweaked the code a little bit so that it will: 1. preserve values that already exist in the object and, 2. rewrite the property if the type of the existing value is not an object.
+1 Clever use of recursion! Just a few details: <strike>you don't have to pass value when you recurse (you never use arguments[1] indeed);</strike> you don't have to rewrite functions, as they can have properties; it will fail if a or b is null (typeof null === "object").

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.