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 badges3 Answers
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
版权声明:本文标题:javascript - How to access dynamic key values of a JSON object in node.js? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744078692a2587226.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论