Home > Web Front-end > JS Tutorial > How to Efficiently Check for Nested JavaScript Object Key Existence?

How to Efficiently Check for Nested JavaScript Object Key Existence?

Linda Hamilton
Release: 2024-12-19 09:17:10
Original
150 people have browsed it

How to Efficiently Check for Nested JavaScript Object Key Existence?

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

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

Example Usage:

var test = {level1:{level2:{level3:'level3'}} };

checkNested(test, 'level1', 'level2', 'level3'); // true
checkNested(test, 'level1', 'level2', 'foo'); // false
Copy after login

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

Example:

console.log(getNested(test, 'level1', 'level2', 'level3')); // 'level3'
Copy after login

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!

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