
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Test for existence of nested JavaScript object key in JavaScript
Suppose, we have a reference to an object −
let test = {};
This object will potentially (but not immediately) have nested objects, something like −
test = {level1: {level2: {level3: "level3"}}};
We are required to write a JavaScript function that takes in one such object as the first argument and then any number of key strings as the arguments after.
The function should determine whether or not the nested combination depicted by key strings exist in the object.
Example
The code for this will be −
const checkNested = function(obj = {}){ const args = Array.prototype.slice.call(arguments, 1); for (let i = 0; i < args.length; i++) { if (!obj || !obj.hasOwnProperty(args[i])) { return false; } obj = obj[args[i]]; }; return true; } let test = { level1:{ level2:{ level3:'level3' } } }; console.log(checkNested(test, 'level1', 'level2', 'level3')); console.log(checkNested(test, 'level1', 'level2', 'foo'));
Output
And the output in the console will be −
true false
- Related Articles
- Get value for key from nested JSON object in JavaScript
- Extract key value from a nested object in JavaScript?
- Check for the existence of key in an object using AngularJS
- Print JSON nested object in JavaScript?
- Javascript search for an object key in a set
- Accessing nested JavaScript objects with string key
- Changing value of nested object keys in JavaScript
- Constructing a nested JSON object in JavaScript
- Recursively list nested object keys JavaScript
- Sum of nested object values in Array using JavaScript
- Checking for Key/Value Existence in Perl Hash
- Filter nested object by keys using JavaScript
- How to modify properties of a nested object in JavaScript?
- Check for the existence of a key in Java IdentityHashMap
- JavaScript - Set object key by variable

Advertisements