Open In App

How to get the Last Nested Property Using JavaScript ?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The last nested property in JavaScript is the innermost property within a hierarchy of nested objects, which can be accessed by traversing through the object.

These are the following ways to get the last nested property using JavaScript:

Method 1: Using recursion

The code iterates through each property of an object recursively. If a property’s value is an object, it continues deeper, otherwise, it stores the property-value pair. It returns the last encountered property.

Example: This example shows the accessing of the last nested property using recursion.

Javascript




function nestedProperty(obj) {
    for (const key in obj) {
        if (typeof obj[key] === 'object') {
            return nestedProperty(obj[key]);
        } else {
            return { [key]: obj[key] };
        }
    }
}
 
const obj = {
    a: {
        b: {
            c: 'Geek'
        }
    }
};
 
const lastNestedProperty = nestedProperty(obj);
console.log(lastNestedProperty);


Output

{ c: 'Geek' }

Method 2: Using Array.is() method

The function iterates through nested properties of an object until it reaches the last property. It checks if the current property is an object and retrieves its keys. Then, it traverses to the last property, ultimately returning the value of the last nested property.

Example: This example shows the accessing of the last nested property using Arrray.is() method.

Javascript




function nestedProperty(obj) {
    let result = obj;
    while (typeof result === 'object' && !Array.isArray(result)) {
        const keys = Object.keys(result);
        // Exit if object has no keys
        if (keys.length === 0) break;
        // Traverse to the last property
        result = result[keys[keys.length - 1]];
    }
    return result;
}
 
// Example
const obj = {
    a: {
        b: {
            c: 'Geeks'
        }
    }
};
 
const lastNestedProperty = nestedProperty(obj);
console.log(lastNestedProperty);


Output

Geeks


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads