Home > database >  How to get the key inside a nested object in react
How to get the key inside a nested object in react

Time:09-15

I have this data in a json file that I need to use in reactjs:

{
  "t": {
    "randomdocid67233": {
      "name": "ABC",
      "latinName": "DEF"
    },
    "randomdocid67234": {
      "name": "GHI",
      "latinName": "JKI"
    }
  }
}

I can get the "t" using Object.keys(data), the "randomdocid67233" using the Object.keys(data[Object.keys(data)[0]]), and the "ABC" using data.t.randomdocid67233[Object.keys(data.t.randomdocid67233)[0]].

But what I want to get is the keys, "name", and "latinName" and store it in an array like this const someVal = ["name", "latinName"].

Is there any way to achieve this? I have spent hours trying to find solution to this like what I found here but the output when I tried it is the values ["ABC", "DEF"].

CodePudding user response:

The following should do the trick:

Object.keys(data.t.randomdocid67233) 

CodePudding user response:

If you want it do be dynamic

const data = {
    "t": {
        "randomdocid67233": {
            "name": "ABC",
            "latinName": "DEF"
        },
        "randomdocid67234": {
            "name": "GHI",
            "latinName": "JKI"
        }
    }
}


const firstObject = data.t[Object.keys(data.t)[0]]
console.log(Object.keys(firstObject))

  • Related