Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access to an object value from array of keys

I have a object like this:

const obj = {
A:{ 
  a1:'vala1', 
  a2:'vala2'
},
B:{
  b1: 'valb1',
  b2: 'valb2'
},
C:{
  c1:{
    c11:'valc11'
  },
  c2:'valc2'
}
}

An array like this const ar = [‘C’,’c1′,’c11′];

How can I get the value identify by concatenation of my array keys? (obj.C.c1.c11)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the following function and pass an object and an array of keys in order to get the corresponding value:

const obj = {
  A:{ 
    a1:'vala1', 
    a2:'vala2'
  },
  B:{
    b1: 'valb1',
    b2: 'valb2'
  },
  C:{
    c1:{
      c11:'valc11'
    },
    c2:'valc2'
  }
}

const arr: string[] = ['C','c1','c11'];

function getVal(obj, arr: string[]) {
  if ( arr.length === 1 ) {
    return obj[arr[0]];   
  }
  return getVal(obj[arr[0]], arr.slice(1));
}

console.log(getVal(obj, arr));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading