admin管理员组

文章数量:1357381

I'm facing issues in retrieving the JSON data.

Here am getting the JSON with dynamic keys. And I need to access that dynamic key's values. The dynamic key is ing from URL and am fetching that key's data from DB.

Here is my sample data.

let roleData = [
  {
    "assetCategory": {
       "canCreate": false,
       "canView": false,
       "canUpdate": false,
       "canDelete": false,
       "isMenu": false,
       "parent": "settings"
     }
  }
]

In the above JSON, I've got assetCategory object. But this value is pletely dynamic. I might get other values too in the place of assetCategory. So without knowing this key, it's getting difficult for me to access the data.

Is there any way to access this dynamic object?

I'm facing issues in retrieving the JSON data.

Here am getting the JSON with dynamic keys. And I need to access that dynamic key's values. The dynamic key is ing from URL and am fetching that key's data from DB.

Here is my sample data.

let roleData = [
  {
    "assetCategory": {
       "canCreate": false,
       "canView": false,
       "canUpdate": false,
       "canDelete": false,
       "isMenu": false,
       "parent": "settings"
     }
  }
]

In the above JSON, I've got assetCategory object. But this value is pletely dynamic. I might get other values too in the place of assetCategory. So without knowing this key, it's getting difficult for me to access the data.

Is there any way to access this dynamic object?

Share Improve this question edited Apr 8, 2020 at 10:00 Aravind asked Apr 8, 2020 at 9:22 AravindAravind 4245 silver badges24 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

let data = [
  {
    "assetCategory": {
       "canCreate": false,
       "canView": false,
       "canUpdate": false,
       "canDelete": false,
       "isMenu": false,
       "parent": "settings"
     }
  }
]


let unknownNames = data.map( item => Object.keys(item)) // returns ['assetCategory']
//Returns array of all the unknown names
console.log(unknownNames);

You should use Object.keys(...) : https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

For example:

const a = [
  {
    "assetCategory": {
       "canCreate": false,
       "canView": false,
       "canUpdate": false,
       "canDelete": false,
       "isMenu": false,
       "parent": "settings"
     }
  }
];

const name = Object.keys(a[0])[0]; // --> "assetCategory"
console.log(a[0][name]) // --> {"canCreate": false, ...}

you can get all keys by Object.keys(data[0].assetCategory). and then data[0].assetCategory[varWithKeyValue] or if it's dynamic data[0].assetCategory['can' + 'Create']

本文标签: javascriptHow to access dynamic key values of a JSON object in nodejsStack Overflow