0

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]])
  }

});
  • 1
    [Tips and tricks](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json). – Teemu Apr 15 '20 at 13:41
  • @Teemu I using dynamic properties to over come multiple if condition and given link i didn't get the expected output. Since I am using dynamically the above code output is like ```msg['d'][d1.text]``` but expected output is ```msg['d'][d1][text]``` or ```msg['d'][d1].text``` – R.Vijayakumar Apr 15 '20 at 15:28
  • When used correctly, the recursive approach will definitely give you all the dynamic properties, unless you're not changing them during the iteration. – Teemu Apr 15 '20 at 15:58
  • okay. My issue is like msg['d'][allMsgType[msg.type]] need to give msg['d'][d1.text] or If I change the format msg['d'][[d1].text] as result it's undefined – R.Vijayakumar Apr 16 '20 at 05:06
  • Done that using lodash get method console.log(_.get(msg, 'd.'+allMsgType[msg.type])); – R.Vijayakumar Apr 16 '20 at 06:32

0 Answers0