

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Safely Accessing Deeply Nested Values In JavaScript
You can use lodash's get method to get properties at any level safely. Getting first-level properties is pretty straightforward. Nested property access is tricky and you should use a tested library like lodash for it.
You can access a deeply nested object in the following way −
Example
let _ = require("lodash"); let obj = { a: { b: { foo: "test" }, c: 2 } }; console.log(_.get(obj, "a.b.foo")); console.log(_.get(obj, "a.c")); console.log(_.get(obj, "a.test")); console.log(_.get(obj, "a.test.x"));
Output
This will give the output −
test 2 undefined undefined
You can also write your own getProp function in the following way −
const getProp = (object, path) => { if (path.length === 1) return object[path[0]]; else if (path.length === 0) throw error; else { if (object[path[0]]) return getProp(object[path[0]], path.slice(1)); else { object[path[0]] = {}; return getProp(object[path[0]], path.slice(1)); } } };
You can use it by passing an array to access the props.
Example
var obj = { level1:{ level2:{ level3:{ name: "Foo" } }, anotherLevel2: "bar" } }; console.log(getProp(obj, ["level1", "level2"]));
Output
This will give the output −
{level3: {name: "Foo"}}
- Related Questions & Answers
- Flattening a deeply nested array of literals in JavaScript
- Query deeply nested Objects in MongoDB
- Accessing nested JavaScript objects with string key
- Accessing and returning nested array value - JavaScript?
- Accessing Values of Strings in Python
- Accessing Values of Lists in Python
- Accessing Values of Tuples in Python
- Accessing Values of Dictionary in Python
- Sum of nested object values in Array using JavaScript
- List all duplicate values in a nested JavaScript object
- Safely setting object properties with dot notation strings in JavaScript
- Accessing a parent Element using JavaScript
- Are array members deeply copied in C++?
- Nested de-structuring in JavaScript.
- Grouping nested array in JavaScript
Advertisements