Skip to content Skip to sidebar Skip to footer

Dynamically Access Object Propertys (js)

I'm trying to access a property of an object dynamically with a string. For example: '.id.public' -> anyObject['id']['public'] The problem - I don't know how many arguments I ha

Solution 1:

The deep-get-set library does what you want:

function get (obj, path) {
  var keys = path.split('.');
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    if (!obj || !hasOwnProperty.call(obj, key)) {
      obj = undefined;
      break;
    }
    obj = obj[key];
  }
  return obj;
}

function set (obj, path, value) {
  var keys = path.split('.');
  for (var i = 0; i < keys.length - 1; i++) {
    var key = keys[i];
    if (deep.p && !hasOwnProperty.call(obj, key)) obj[key] = {};
    obj = obj[key];
  }
  obj[keys[i]] = value;
  return value;
}

Solution 2:

Yet another way for setting value

functionsetVal(obj, path, val){
    var paths = path.split('.'),
        curProp = obj;

    for(var i=0;i<paths.length-1;i++){
        curProp = curProp[paths[i]];
    }
    curProp[paths[i]] = val;

}

and use it like

setVal(anyObj, "id.public", 'newValue');

Solution 3:

You can't do that without the help of a little code like this:

var mapToProperty = function(obj, path, value) {
        if (!path) return obj;

        var parts = path.split("."),
           p = parts[0],
           v = (typeof obj[p] === "function") ? obj[p](value) : (parts.length !==1 || !value) ? obj[p] : (obj[p] = value), value ;
           if (parts.length == 1) return v;
               returnmapToProperty(v, parts.slice(1).join("."), value);
}

// use it like thisvar myvalue = mapToProperty(myObj, "address.street")

// you can map into your objects as far as you want. obj1.obj2.obj3.prop// you can set as well :-)mapToProperty(myObj, "address.street", "This is great!")

Post a Comment for "Dynamically Access Object Propertys (js)"