Nested JavaScript Object Key Existence Test
Identifying the existence of deeply nested object properties can be a challenge. When attempting to use dot notation to access a multi-level key, errors can occur if any intermediate level is undefined or null.
Existing Approach:
One common approach is to manually check for each level of the nested object using conditional statements, ensuring that every level exists before accessing the desired key. However, this method can become tedious and error-prone for deeply nested objects.
Better Option:
A more robust solution is to create a function that recursively checks the existence of nested keys. The function takes the object and a series of level names as arguments and iterates through each level, verifying if it exists and its value is not undefined or null.
Function Implementation:
Here's a step-by-step function implementation:
function checkNested(obj /*, level1, level2, ... levelN*/) { var args = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < args.length; i++) { if (!obj || !obj.hasOwnProperty(args[i])) { return false; } obj = obj[args[i]]; } return true; }
This function returns true if all the specified levels exist and false otherwise.
ES6 Update:
In ES6, a more concise version of this function is possible using recursion and tail call optimization:
function checkNested(obj, level, ...rest) { if (obj === undefined) return false if (rest.length == 0 && obj.hasOwnProperty(level)) return true return checkNested(obj[level], ...rest) }
Example Usage:
var test = {level1:{level2:{level3:'level3'}} }; checkNested(test, 'level1', 'level2', 'level3'); // true checkNested(test, 'level1', 'level2', 'foo'); // false
Value Retrieval (ES6):
Additionally, to retrieve the value of a nested property, the following one-line function can be used:
function getNested(obj, ...args) { return args.reduce((obj, level) => obj && obj[level], obj) }
Example:
console.log(getNested(test, 'level1', 'level2', 'level3')); // 'level3'
The above is the detailed content of How to Efficiently Check for Nested JavaScript Object Key Existence?. For more information, please follow other related articles on the PHP Chinese website!