Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables with nested Javascript object

Tags:

javascript

Suppose I have this:

var a = { A : { AA : 1 }, B : 2 };

Is there a way for me to create a variable that could allow me to reference either AA or B? What would the syntax look like?

// I know I can do this:    
a['B']; // 2
a['A']['AA']; // 1

// something like this?
var myRef = ???;
a[myRef]; 1 or 2 depending on myRef

If not, what's a better way to get what I'm going for here?

like image 962
Ben Flynn Avatar asked Jan 05 '12 21:01

Ben Flynn


3 Answers

Not directly.

Solution 1 - use object flattening

Flatten object, to have new object var a = { 'A.AA' : 1; B : 2 };.

See compressing object hierarchies in JavaScript or Flattening a complex json object for mvc binding to get the javascript function for it.

Soution 2 - write key-path accessor

I can see it was already addressed by Eugen. Reposted code-reviewed version:

function Leaf(obj,path) {
  path=path.split('.');
  var res=obj;
  for (var i=0;i<path.length;i++) res=res[path[i]];
  return res;
}

Solution 3 - use eval

var x = eval("a." + myRef); // x will be 1 for myRef == "A.AA", 2 for "B"

Be careful with this solution as you may introduce some security issues. It is more of the curiosity.

like image 178
Krizz Avatar answered Sep 23 '22 06:09

Krizz


Since i also encounter this problem, i wrote also a one line util for this (ES6):

const leaf = (obj, path) => (path.split('.').reduce((value,el) => value[el], obj))

Example:

const objSample = { owner: { name: 'Neo' } };
const pathSample = 'owner.name';

leaf(objSample, pathSample) //'Neo'
like image 32
Maximiliano Cespedes Avatar answered Sep 22 '22 06:09

Maximiliano Cespedes


function Leaf(obj,path) {
  path=path.split('.');
  var res=obj;
  for (var i=0;i<path.length;i++) obj=obj[path[i]];
  return res;
}

Leaf(a,'B')=2

Leaf(a,'A.AA')=1

Decorate with error handling etc. according to your needs.

like image 31
Eugen Rieck Avatar answered Sep 22 '22 06:09

Eugen Rieck