0

When I execute following script,

js

 const displayTooltip = () => {
    const json = {
        "tooltipInfo":{
            "caseNo":"test",
            "caseNumber":"test2"
        }
    }
    console.log(json.tooltipInfo)
    for (var key in json.tooltipInfo) {
        console.log("key",key)
        console.log("value",json.tooltipInfo.key)
    }
}

following is displayed

key caseNo
value undefined
key caseNumber
value undefined

I wonder why value is undefined.

What is the root cause of this ? If someone has opinion,will you please let me know

Thanks

Heisenberg
  • 4,787
  • 9
  • 47
  • 76

1 Answers1

0

You are using dot notation to access the value of the key, but you need to use bracket notation.

This is because the key is a variable, and dot notation only works with literal strings.

console.log(json.tooltipInfo.key) // undefined
console.log(json.tooltipInfo[key]) // test

You can also use Object.keys() to get the keys of an object, and then use bracket notation to access the values.

const keys = Object.keys(json.tooltipInfo)
for (var key of keys) {
  console.log("key", key)
  console.log("value", json.tooltipInfo[key])
}
Nuro007
  • 157
  • 12