My sample code its working fine if the properties data. It's undefined if properties deep length is more than one like d1.text or d1.title. Is there any other way to get value with dynamic properties. I am doing this way to reduce the code and avoid mulitple if else condition. Get value from object multiple dynamic properties name in Javascript
let allMsgType = {
'a1': 'data',
'a2': `d1.title`,
'a3': `d2.text`
}
let dynamic = [{
type: 'a2',
d: {
d1: {
title: 'test'
}
}
},{
type: 'a3',
d: {
d2: {
text: 'test2'
}
}
},{
type: 'a1',
d: {
data: 'test3'
}
},{
type: 'a2',
d: {
d1: {
title: 'test'
}
}
}];
dynamic.forEach(msg => {
if (msg.type in allMsgType) {
console.log('\x1b[32m%s\x1b[0m', allMsgType[msg.type])
console.log('\x1b[32m%s\x1b[0m', JSON.stringify(msg, '', 4))
console.log('\x1b[32m%s\x1b[0m', msg['d'][allMsgType[msg.type]])
}
});