What is dottie?
The dottie npm package is a utility for safely reading and writing deep properties of objects in JavaScript. It uses dot notation strings to access deeply nested properties and provides a set of functions to manipulate these properties without worrying about whether the intermediate properties exist.
What are dottie's main functionalities?
Get
Retrieve the value of a nested property using a dot notation string.
const dottie = require('dottie');
const value = dottie.get({a: {b: {c: 'd'}}}, 'a.b.c'); // 'd'
Set
Set the value of a nested property using a dot notation string. If intermediate properties do not exist, they are created.
const dottie = require('dottie');
const obj = {};
dottie.set(obj, 'a.b.c', 'd'); // obj is now {a: {b: {c: 'd'}}}
Transform
Transform an object with dot notation string keys into a nested object structure.
const dottie = require('dottie');
const obj = { 'a.b.c': 'd' };
const transformed = dottie.transform(obj); // transformed is now {a: {b: {c: 'd'}}}
Exists
Check if a nested property exists within an object using a dot notation string.
const dottie = require('dottie');
const exists = dottie.exists({a: {b: {c: 'd'}}}, 'a.b.c'); // true
Paths
Get an array of dot notation paths for all properties in an object.
const dottie = require('dottie');
const paths = dottie.paths({a: {b: {c: 'd'}}}); // ['a.b.c']
Other packages similar to dottie
lodash.get
lodash.get is a method from the Lodash library that allows you to access deep properties of an object safely. It is similar to dottie's get function but is part of a larger utility library.
deep-get-set
deep-get-set is a small library that provides get and set functions for deep properties of an object, similar to dottie. It does not have as many features as dottie but is lightweight.
object-path
object-path is another utility that provides access to deep properties using a similar dot notation. It offers a rich set of methods like dottie and includes additional functionality such as del (delete) and has (check existence).
Install
npm install dottie
Usage
For detailed usage, check source or tests.
Get value
Gets nested value, or undefined if unreachable.
var values = {
some: {
nested: {
key: 'foobar';
}
}
}
dottie.get(values, 'some.nested.key'); // returns 'foobar'
dottie.get(values, 'some.undefined.key'); // returns undefined
Set value
Sets nested value, creates nested structure if needed
dottie.set(values, 'some.nested.value', someValue);
Transform object
Transform object from keys with dottie notation to nested objects
var values = {
'user.name': 'Mick Hansen',
'user.email': 'mh@innofluence.com',
'user.professional.title': 'Developer',
'user.professional.employer': 'Innofluence'
};
var transformed = dottie.transform(values);
transforms is now equal to =
{
user: {
name: 'Mick Hansen',
email: 'mh@innofluence.com',
professional: {
title: 'Developer',
employer: 'Innofluence'
}
}
}