Populate object from string

Create a JSON object from a string.

by kshep92

JavaScript

console.clear();

const body = { 
'name': 'Johnathan Freeloader',
'address.line_1': '#123 Home Street',
'address.line_2': 'Alabama',
'address.city.id': 'AL',
'address.city.name': 'Alabama',
'address.city.state.foo.bar': 'baz',
'address.city.state.foo.baz': 'bar',
'address.city.population.size': 3000,
'address.city.population.density': 1.8,
'likes': ['fishing', 'driving', 'singing']
};

/*
{ 
 name: '', 
 address: {
   line_1: '',
   line_2: '',
   city: {
     id: '',
     name: ''
   }
 },
 likes: []
}
*/

let result = {};

const keys = Object.keys(body);

keys.forEach(key => {
	let components = key.split('.');
  const root = components[0];
  components.shift(); // Remove the first element in the array
  if(components.length == 0) {
  	result[root] = body[key];
    return;
  }
  let newObj = result[root] == undefined ? {} : result[root];
  components.reduce((obj, _key, idx, arr) => {
  	if(obj[_key] != undefined) return obj[_key];
    
    // If we're at the last item of the array
    const lastElement = arr[idx + 1] == undefined;
    obj[_key] = lastElement ? body[key] : {};
    return obj[_key];	
  }, newObj);
  Object.assign(result, { [root] : newObj });
});
console.log(result);