1

Just curious how this would be accomplished in Javascript? Lets say I have an object such as

var obj = {
  'foo.bar.baz': 'valueA',
  'foo.bar.qux': 'valueB'
};

How can I iteratively turn these into a nested object such as

console.log(obj.foo.bar.baz); // valueA
console.log(obj.foo.bar.qux); // valueB

It would be something like this I think?

var ret=[];
for (var key in obj)
{
  var parts = key.split('.');

  for (var i in parts)
  {
    if (parts.hasOwnProperty(i))
    {
      // do something?
    }
  }
  ret.push(something);
}
0

2 Answers 2

1

An alternative version:

var obj = {
  'foo.bar.baz': 'valueA',
  'foo.bar.qux': 'valueB'
};

var obj2 = {};

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {

    var parts = key.split('.');
    var head = obj2;

    var limit = parts.length - 1;
    for (var i = 0; i < limit; i++) {
      var part = parts[i];
      head = head[part] || (head[part] = {});
    }
    head[parts[limit]] = obj[key];
  }
}

obj2 // =>
{ 
  foo: {
    bar: {
      baz: "valueA",
      qux: "valueB"
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Once you have the string (i.e. 'foo.bar.baz'), you can recursively call a function which creates a new object;

Example:

function buildObject(treeElements, value)
{
    var object = {};
    if(treeElements.length == 1)
    {
        object[treeElements.shift()] = value;
    }
    else
    {
        object[treeElements.shift()] = buildObject(treeElements, value);
    }
    return object;
}

Simply pass it the array from your split() and the final value it should have.

2 Comments

If this where to be used, an additional "merge" step would be required to produce the OP's result
OP should be able to figure out that step himself...however I guess he preferred the lazy way -_-'

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.