2

I want convert a dot notation string like 'a.b.c.d' to an Object. If the Object doesnt exist I want create a empty one.

var str = 'a.b.c.d'
var obj = {}

// so ...

function dotToObj(obj, str) {
    // something 
    obj[?] = obj[?] || {}            
     }

// If object doesnt exist so create a empty object.

var rsp = dotToObj(obj, str);


console.log(rsp)

// Excpect:
Object {a: Object}
    a: Object
        b: Object
            c: Object
                d: Object
                __proto__: Object
            __proto__: Object
        __proto__: Object
    __proto__: Object

1 Answer 1

7

You can split the string and use the parts for the reference with Array.prototype.reduce(), where obj is used as the start object and while iterating, the new reference is returned.

var str = 'a.b.c.d',
    obj = {};

str.split('.').reduce(function (r, a) {
    r[a] = r[a] || {};
    return r[a];
}, obj);

document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');

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

2 Comments

how can I set value for deepest value, example d = 123?
@huykon225, you could take s/t like this: stackoverflow.com/questions/55635011/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.