Public
Snippet $23 authored by Jabis Sevón

topath-frompath.js

var typeOf = function(o) {
    return Object.prototype.toString
      .call(o).match(/(\w+)\]/)[1].toLowerCase();
};
  
var fromPath = function(obj, path) {
    path = path.replace(/\[(\w+)\]/g, '.$1');
    path = path.replace(/^\./, '');
    var a = path.split('.');
    //console.log(obj,path);
    while (a.length) {
      var n = a.shift();
      if (obj && n in obj)
        obj = obj[n];
      else
        return;
    }
    return obj;
  };
  var toPath = function(obj, path, value) {
    if (typeOf(path) == "string")
      var path = path.replace(/\[(\w+)\]/g, '.$1').replace(/^\./, '').split('.');
    if (path.length > 1) {
      var p = path.shift();
      if (obj[p] == null) {
        if (p.test(/^\d$/) || (path.length > 0 && path[0].test(/^\d$/))) {
          obj[p] = [];
        } else if (!p.test(/^\d$/) && typeOf(obj[p]) != 'object') {
          obj[p] = {};
        }
      }
      toPath(obj[p], path, value);
    } else {
      var p = path.shift();
      if (p.test(/^\d$/) || typeOf(obj[p]) == "array") {
        if (!obj[p] && typeOf(value) == "array") obj[p] = value;
        else if (!obj[p] && typeOf(value) == "string") obj[p] = [value];
        else obj[p] = value;
      } else {
        obj[p] = value;
      }
    }
  };