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