-1

I will be getting a dynamic json as response, so I am using the below to get the key names and I always want the third key value which will either be true or false. So i get the third key's value using the below which is stored inside the theTypeIs and when I try to access the json I get undefined

example Json

submitResult = [{
        ComodityID: 33,
        ComodityName: 'LED',
        field1: true
    }, {
        ComodityID: 342,
        ComodityName: 'Installing ',
        field1: true
    }, {
        ComodityID: 322,
        ComodityName: ' Bracket',
        field1: true
    }
]

To find the third key name in the dynamic json:

var theTypeIs = Object.keys(submitResult[i])[2];
console.log(submitResult[i].theTypeIs)

I get undefined when i console log it. Can someone help me on this. Thank you in advance.

Victor
  • 5,493
  • 1
  • 27
  • 28
yosup
  • 9
  • 3
  • By the way, you should note that `Object.keys` doesn't guarantee the order. So you may get unexpected results. Check https://stackoverflow.com/q/30076219 for more info. – Victor Dec 13 '18 at 19:49

3 Answers3

2

console.log(submitResult[i].theTypeIs) prints undefinedbecause there is no property theTypeIs of submitResult[i]

You need to use the bracket notation when accessing an attribute by a variable

console.log(submitResult[i][theTypeIs])
simon.ro
  • 2,984
  • 2
  • 22
  • 36
0

You should use the bracket notation:

console.log(submitResult[i][theTypeIs]);
Victor
  • 5,493
  • 1
  • 27
  • 28
-1
enter code 

const submitResult= [{ ComodityID: 33, ComodityName: 'LED', field1: true }, { ComodityID: 342, ComodityName: 'Installing ', field1: true }, { ComodityID: 322, ComodityName: ' Bracket', field1: true }]


//To get the third key which is field1

you can run a loop i to length
const {field1} = submitResult[i];
  • That code snippet doesn't run correctly. Please fix it, and also add text to describe why it answers the question. – Ken Y-N Dec 14 '18 at 04:25