Home >Web Front-end >JS Tutorial >How Can I Safely Check for the Existence of Nested Keys in JavaScript Objects?
Testing the Existence of Nested JavaScript Object Keys
Verifying the existence of properties within nested JavaScript objects poses a challenge, especially when faced with potential null or undefined values. To address this issue, consider employing a step-by-step approach instead of relying on the risky and error-prone direct property access.
One viable solution involves a tailored function that tests the presence of multiple nested levels. This function, elegantly named checkNested, accepts the target object as its first argument, followed by a series of expected nested property names. It systematically checks for the existence of each property, returning true if all are found and false otherwise.
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; }
For instance, given the object:
var test = { level1: { level2: { level3: 'level3', }, }, };
Calling checkNested with the expected levels returns the anticipated results:
checkNested(test, 'level1', 'level2', 'level3'); // true checkNested(test, 'level1', 'level2', 'foo'); // false
ES6 Optimizations
Harnessing ES6 features can streamline this function further, resulting in a concise and efficient implementation. Recursion and tail call optimization combine to create a succinct yet powerful solution:
function checkNested(obj, level, ...rest) { if (obj === undefined) return false; if (rest.length == 0 && obj.hasOwnProperty(level)) return true; return checkNested(obj[level], ...rest); }
In addition, if your goal is to retrieve the value of a nested property instead of merely testing its existence, a more straightforward approach is available:
function getNested(obj, ...args) { return args.reduce((obj, level) => obj && obj[level], obj); } const test = { level1: { level2: { level3: 'level3', }, }, }; console.log(getNested(test, 'level1', 'level2', 'level3')); // 'level3' console.log(getNested(test, 'level1', 'level2', 'level3', 'length')); // 6 console.log(getNested(test, 'level1', 'level2', 'foo')); // undefined console.log(getNested(test, 'a', 'b')); // undefined
By leveraging these techniques, you can navigate the complexities of nested JavaScript objects with confidence, ensuring the robustness and reliability of your code.
The above is the detailed content of How Can I Safely Check for the Existence of Nested Keys in JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!