ehime
ehime

Reputation: 8375

Building dynamic objects from split()?

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);
}

Upvotes: 1

Views: 59

Answers (2)

sabof
sabof

Reputation: 8192

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"
    }
  }
}

Upvotes: 1

weeknie
weeknie

Reputation: 170

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.

Upvotes: 0

Related Questions