Joe
Joe

Reputation: 4234

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?

Upvotes: 0

Views: 472

Answers (2)

Nenad Vracar
Nenad Vracar

Reputation: 122047

You can first loop object using for...in loop and then split each key at . and use reduce to build object.

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

var result = {}
for (var k in input) {
  k.split('.').reduce(function(r, e, i, arr) {
    return r[e] || (r[e] = arr[i + 1] ? {} : input[k])
  }, result)
}

console.log(result)

Upvotes: 1

kukkuz
kukkuz

Reputation: 42352

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

Upvotes: 1

Related Questions