Testing Existence of Nested JavaScript Object Keys
When inspecting deeply nested JavaScript objects, checking for the presence of specific keys can become a challenge. The standard approach involves sequential checks, but this can be both cumbersome and prone to errors.
A more robust solution is to utilize recursive functions that navigate the object structure step by step. For example:
function checkNested(obj, ...levels) { for (var i = 0; i < levels.length; i++) { if (!obj || !obj.hasOwnProperty(levels[i])) { return false; } obj = obj[levels[i]]; } return true; }
This function takes an object and an arbitrary number of levels as arguments. It iterates through the levels, checking if each corresponding key exists and increments the object pointer. If any key is missing or the object is undefined, it returns false; otherwise, it returns true.
Example usage:
const test = { level1: { level2: { level3: 'level3' } } }; checkNested(test, 'level1', 'level2', 'level3'); // true checkNested(test, 'level1', 'level2', 'foo'); // false
Alternatively, ES6 can be leveraged to simplify the recursive function:
function checkNested(obj, level, ...rest) { if (obj === undefined) return false; if (rest.length == 0 && obj.hasOwnProperty(level)) return true; return checkNested(obj[level], ...rest); }
However, to retrieve the value of a deeply nested property, a one-line function can be used:
function getNested(obj, ...args) { return args.reduce((obj, level) => obj && obj[level], obj); } 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
The above is the detailed content of How Can I Efficiently Check for the Existence of Nested Keys in a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!