Katharine Osborne Katharine Osborne - 6 months ago 19
JSON Question

How to translate a string to object notation

I'm working with a JSON validator that checks a give JSON object against a schema and returns errors if it doesn't match. One of the things I need to do is add missing attributes, but these could potentially be quite deep in the structure. The validator error returns the location of a missing attribute as a string in this format:


I can strip out the "data." bit easily enough, but I don't know how to translate the rest to correct object notation, in any depth. This is what I've got so far:

var attributeLineage = newField.split(".");
obj[attributeLineage[0]][attributeLineage[1]] = "";

So obviously this only works when there are only two levels of depth. I need to loop through the values in attributeLineage and link them all together to correctly construct the missing attribute in the given object, at any depth. How can this be done?

I might be missing something totally obvious, or going about it the wrong way, but I'm not sure how to proceed.


Using reduce() method get the reference of the inner object and update the property using last element in split array.

var newField = 'data.thing1.thing2.thingN';
// split the string
var attributeLineage = newField.split("."),
  // get last element and remove it from splitted array
  prop = attributeLineage.pop();

var ob = {
  data: {}

// get the object reference
var obj = attributeLineage.reduce(function(o, k) {
  // return if nested object is defined 
  // else define and return it
  return o[k] || (o[k] = {}) && o[k];
}, ob);

// update the inner object property
obj[prop] = "hi";