1

Suppose I have an object

var obj = {
   subObj : {
     value : 1
   }
};

Is there any way to get obj.subObj.value using a complex property-name string that goes to sub objects?

Example (that doesn't work)

var attr = "subObj.value";
return obj[attr]; 
jozenbasin
  • 2,142
  • 2
  • 14
  • 22

2 Answers2

1

No you can't.


You can split and loop over every attr.

var obj = {
   subObj : {
     value : 1
   }
};

var attr = "subObj.value";

var result = obj;
attr.split('.').forEach((c) => result = result[c]);

console.log(result);

Or you can use reduce:

var obj = {
   subObj : {
     value : 1
   }
};

var attr = "subObj.value";
var result = attr.split('.').reduce((a, c) => a[c], obj);
console.log(result);
Ele
  • 33,468
  • 7
  • 37
  • 75
1

There is no notation to do this in JavaScript but you could use something like this:

var obj = {
   subObj : {
     value : 1
   }
};
var attr = "subObj.value";
var result = attr.split(".").reduce((a, c) => a[c], obj);
console.log(result)
Titus
  • 22,031
  • 1
  • 23
  • 33