0
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?

0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Any specific reason to use Object.create(null) instead of the literal {}? He never clarified if he's using the output object as a simple map
nope, but Object.create(null) does not inherit the prototype... it doesn't matter here though :)
1

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)

Comments

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.