Skip to content Skip to sidebar Skip to footer

Js Reference Multi-layered Dynamic Object String

Suppose I have a string that references a deep Javascript object, such as: var string = 'response.basicInfo.gender'; I want to build a function that safely checks if that object e

Solution 1:

Plus 1 to Bergi, who linked to a page with six links, one of which had an answer I adapted to solve the problem:

Convert JavaScript string in dot notation into an object reference

Here's the full solution.

// We want to run a parse function to convert// the object response.basicInfo.gender (which is 'M')// to 'Male', etc.// Sets the value of a string representing a deep object.setDeep: function(root, path, value) {
  var parts = path.split('.'), obj = root;
  for (var i = 0; i < parts.length - 1; ++i) {
    obj = obj[parts[i]] || { };
  }
  obj[parts[parts.length - 1]] = value;
  return obj;
},

// Gets the value of a string representing a deep object.getDeep: function(root, path) {
  var parts = path.split('.'), obj = root, target;
  for (var i = 0; i < parts.length; ++i) {
   target = obj[parts[i]];
   if (typeof target == "undefined") returnvoid0;
   obj = target;
  }
  return obj;
},

// Loops through multiple string representations// of deep objects and runs the values through // assigned parsing functions for each of them,// returning the root object.parseHelper: function(obj, items) {
  for (item in items) {
    var val = getDeep(obj, item);
    var func = items[item];
    if (val !== undefined) {
      val = func(val);
    }
    setDeep(obj, item, val);
  }
  return obj;
},

// response.basicInfo.gender = 'M';// response.foo.bar = true;

response = parseHelper(response, {
  'basicInfo.gender': function(val){
    return (val == 'M') ? 'Male' : (val == 'F') ? 'Female' : val;
  },
  'foo.bar': function(val) {
    return (val) ? false : true;
  },
});

// response.basicInfo.gender = 'Male';// response.foo.bar = false;

Post a Comment for "Js Reference Multi-layered Dynamic Object String"