1

I was wondering if this was possible without eval (i hear it's evil).

var myString = 'myObject.property.subproperty';

and convert it to

var obj = {
    myObject: {
        property: {
            subproperty: {}
        }
    }
};

Been at this for 2 hours.

The val solution that I don't like:

I can do it with input string.

var myString = 'myObject.property.subproperty';
var nameTree = myString.split('.');
var evalString = '';
var myObj = {};
_.forEach(nameTree, function(value, key){

    if (key == 0) {
        evalString += 'myObj[' + value + '] = {};';
    } else {
        evalString += '[' + value + '] = {};';
    }
});

eval(evalString);

I get:

console.log(myObj);

// {myObject: {property:{subproperty:{}}}};
4
  • 1
    basically, given that input, you'll have to do it yourself. you can just use a self made function using split in a recursive fashion Commented Jul 9, 2014 at 17:35
  • 1
    I'm not sure what eval() has to do with your question because you can't even use it to make what you want from your input string. Anyway, here's a working demo: jsfiddle.net/jfriend00/Q9cWa using the same technique hugomg showed (who happens to type faster than I so posted an answer sooner). My version is put into a function. Commented Jul 9, 2014 at 17:40
  • @jfriend00 edited question to show the eval solution I mentioned. But it's evil. I burned it before it laid eggs. Commented Jul 9, 2014 at 19:48
  • OK, yep that's evil. That's even more complicated than not using eval(). Commented Jul 9, 2014 at 19:52

1 Answer 1

3

The feature you can use to solve your problem is dynamic property access using string indexing. obj["foo"] is the same as obj.foo.

var properties = myString.split('.');
var obj = {};
var curr = obj;
for(var i=0; i<properties.length; i++){
    var next = {}
    curr[properties[i]] = next;
    curr = next;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This would give me a flat object. Or you pressed enter too fast?

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.