
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
Safely Setting Object Properties with Dot Notation Strings in JavaScript
You can use lodash's set method to set properties at any level safely. Setting first-level properties are pretty straightforward. Nested property access is tricky and you should use a tested library like lodash for it.
You can set a deeply nested object in the following way −
Example
let _ = require("lodash"); let obj = { a: { b: { foo: "test" }, c: 2 } }; _.set(obj, "a.b.foo", "test1"); _.set(obj, "a.c", { test2: "bar" }); console.log(obj);
Output
This will give the output −
{ a: { b: { foo: 'test1' }, c: { test2: 'bar' } } }
You can also write your own setUpdateProp function in the following way −
const setUpdateProp = (object, path, value) => { if (path.length === 1) object[path[0]] = value; else if (path.length === 0) throw error; else { if (object[path[0]]) return setUpdateProp(object[path[0]], path.slice(1), value); else { object[path[0]] = {}; return setUpdateProp(object[path[0]], path.slice(1), value); } } };
You can use it by passing an array to access the props.
Example
var obj = { level1:{ level2:{ level3:{ name: "Foo" } }, anotherLevel2: "bar" } }; setUpdateProp(obj, ["level1", "level2"], "FooBar"); console.log(obj);
Output
This will give the output −
{ level1: { level2: 'FooBar', anotherLevel2: 'bar' } }
Advertisements