Dynamically access object propertys (JS) [duplicate]

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 have (for example ".id" or ".id.public" or ".id.public.whatever".

I made a little workaround:

var currentSplit = anyObject;
var splitted = "id.public".split("\.");
splitted.forEach(function(s) { currentSplit = currentSplit[s]; });

When I try now to override the object property I will override the reference and not the object property.

currentSplit = "test";

I tried already stuff like anyObject["id.public"] = "test"; but it didn't work.



Yet another way for setting value

function setVal(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');

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;
    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;

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;
               return mapToProperty(v, parts.slice(1).join("."), value);

// use it like this

var 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!")


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.