Home > Web Front-end > JS Tutorial > How Can I Efficiently Check for the Existence of Nested Keys in a JavaScript Object?

How Can I Efficiently Check for the Existence of Nested Keys in a JavaScript Object?

Linda Hamilton
Release: 2025-01-01 07:09:11
Original
608 people have browsed it

How Can I Efficiently Check for the Existence of Nested Keys in a JavaScript Object?

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;
}
Copy after login

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
Copy after login

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);
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template