
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Test for Existence of Nested JavaScript Object Key
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
Advertisements