Per Ström Per Ström - 11 months ago 88
Javascript Question

Create nested object from object with multiple strings, javascript

var input = {
"id": 'AB',
"specified.name": 'some name',
"specified.manufacturer": 'some manufacturer',
"specified.environment.state": 'good'
}

/**
var expectedOutput = {
id:'AB',
specified: {
name: 'some name',
manufacturer: 'some manufacturer',
environment: {
state: 'good'
}
}
};
**/


https://jsbin.com/senehijula/edit?html,js,output

I'm aware there are some similar questions but not really like this one.

Any elegant way of doing this?

Answer Source

Well, you can split the strings and loop through to create the required data structure - see a demo below:

var input = {
  "id": 'AB',
  "specified.name": 'some name',
  "specified.manufacturer": 'some manufacturer',
  "specified.environment.state": 'good'
}

var output = {};
Object.keys(input).forEach(function(e){
  let keys = e.split('.');
  let key = keys.pop();
  let obj = keys.reduce(function(p,k){
    p[k] = p[k] || Object.create(null);
    return p[k];
  }, output);
  obj = obj || Object.create(null);
  obj[key] = input[e];
});

console.log(output);
.as-console-wrapper{top:0;max-height:100%!important;}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download