最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to access dynamic key values of a JSON object in node.js? - Stack Overflow

programmeradmin0浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论