简体   繁体   中英

How to access dynamic key values of a JSON object in node.js?

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 coming 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 completely 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?

You should use Object.keys(...) : https://developer.mozilla.org/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, ...}

 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 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM