In my application, we have a method that accepts JSON and path which tell us which object we need to get from that JSON. Buth both JSON and path are dynamic, I can't predict that every time we get a request we are getting the same JSON and path.
Example:
{
"company": {
"employees": {
"employee": {
"department": {
"departmentId": 1,
"departmentName": "Developer"
},
"employeeDetails": {
"id": 1,
"name": "abc"
}
}
}
}
}
and the path is company.employees.employee.department. And the requirement is when I get this path I only need that nested JSON object with employee details.
Expected output:
{
"company": {
"employees": {
"employee": {
"department": {
"departmentId": 1,
"departmentName": "Developer"
}
}
}
}
}
CodePudding user response:
I am confused about your requirement. There is ambiguity in your question. I am thinking that you want to access employeeDetails from the JSON. Here is the solution for that:
var data = {
"company": {
"employees": {
"employee": {
"department": {
"departmentId": 1,
"departmentName": "Developer"
},
"employeeDetails": {
"id": 1,
"name": "abc"
}
}
}
}
}
var employee = data.company.employees.employee // this will store the nested json which is having employeeDetails
console.log(employee)// nested JSON with employeeDetails
console.log(employee.employeeDetails)// this will give you the employeeDetails
CodePudding user response:
The method may look like:
const getData = (json, path) => {
let current = json;
const keys = path.split('.');
for (let key of keys) {
if (!current) {
break;
}
current = current[key];
}
return current;
};
getData(yourJSON, 'key1.key2.key3');