https://github.com/nash403/set-safe
safe access to deeply nested properties and functions in JS objects without getting a TypeError
https://github.com/nash403/set-safe
Last synced: 14 days ago
JSON representation
safe access to deeply nested properties and functions in JS objects without getting a TypeError
- Host: GitHub
- URL: https://github.com/nash403/set-safe
- Owner: nash403
- Created: 2016-10-18T11:57:45.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2016-10-18T19:26:37.000Z (almost 9 years ago)
- Last Synced: 2025-03-08T08:48:10.476Z (7 months ago)
- Language: JavaScript
- Size: 14.6 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# set-safe
#### Safely set value at property, create intermediate properties if necessary, without getting an Error if a parent is undefined.
***
You can even whether alter the original object or create an altered copy of it.
***
#### Install:
`npm install set-safe --save`#### How to use
```JavaScriptconst set = require ('set-safe');
const toto = {
foo: {
bar: {
baz: ['winter','is','coming'],
fifo (arg1, arg2) {
return 42;
}
},
astring: "John Doe"
}
};// Tests
let i = 1;
console.log('The tested object is:', JSON.stringify(toto));console.log(`\nExample ${i}:\n`,
JSON.stringify(set('foo.bar.baz.2','there', toto))); // sets "coming" to "there"console.log(`\nExample ${++i}:\n`,
JSON.stringify(set('foo.astring','Leonardo Di Caprio', toto))); // sets "astring" propertyconsole.log(`\nExample ${++i}:\n`,
JSON.stringify(set(['opt1','sub1','subsub1','subsubsub1'].join('.'),'a value'))); // creates a new object with nested propsconsole.log(`\nExample ${++i}:\n`,
JSON.stringify(set('foo.inexistant.property',42,toto))); // adds a new propertyconsole.log(`\nExample ${++i}:\n`,
JSON.stringify(set('foo.bar.baz.fifo',42,toto, true)), ' - ',JSON.stringify(toto)); // creates an altered copy of toto object
```
The browser version adds `setSafe` to the *window* object.