I have an array of objects in which I want to get the value of a key for e.g. 'variable'. But the depth of the key is varying, like it could be as follows -
[{
"test": {
"nameObj": {
"name": "DateExpires",
"title": "DateExpires",
"variable": "DateTime"
},
}
},
{
"test": {
"nameObjSomethingElse": {
"name": "DateExpires",
"title": "DateExpires",
"variable": "DateTime"
},
}
},
{
"test": {
"nameObjSomethingElse": {
"name": "DateExpires",
"title": "DateExpires",
"anotherLevel": {
"variable": "DateTime"
}
}
}
}]
Run Code Online (Sandbox Code Playgroud)
In each object in the array key 'variable' is at different level and under different key. How can I get the value of 'variable'?
You could use JSON.stringify and use its callback function to identify every value of a particular key:
const obj = [{
"test": {
"nameObj": {
"name": "DateExpires",
"title": "DateExpires",
"variable": "DateTime"
},
}
},
{
"test": {
"nameObjSomethingElse": {
"name": "DateExpires",
"title": "DateExpires",
"variable": "DateTime"
},
}
},
{
"test": {
"nameObjSomethingElse": {
"name": "DateExpires",
"title": "DateExpires",
"anotherLevel": {
"variable": "DateTime"
}
}
}
}];
const variables = [];
JSON.stringify(obj, (key, val) => {
if (key === 'variable') {
variables.push(val);
}
return val;
});
console.log(variables);Run Code Online (Sandbox Code Playgroud)
Or, if you wanted to recurse more manually:
const obj = [{
"test": {
"nameObj": {
"name": "DateExpires",
"title": "DateExpires",
"variable": "DateTime"
},
}
},
{
"test": {
"nameObjSomethingElse": {
"name": "DateExpires",
"title": "DateExpires",
"variable": "DateTime"
},
}
},
{
"test": {
"nameObjSomethingElse": {
"name": "DateExpires",
"title": "DateExpires",
"anotherLevel": {
"variable": "DateTime"
}
}
}
}];
const recurse = (obj, arr=[]) => {
Object.entries(obj).forEach(([key, val]) => {
if (key === 'variable') {
arr.push(val);
}
if (typeof val === 'object') {
recurse(val, arr);
}
});
return arr;
};
console.log(
recurse(obj)
);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41 次 |
| 最近记录: |