• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# dot-prop [![Build Status](https://travis-ci.org/sindresorhus/dot-prop.svg?branch=master)](https://travis-ci.org/sindresorhus/dot-prop)
2
3> Get, set, or delete a property from a nested object using a dot path
4
5
6## Install
7
8```
9$ npm install --save dot-prop
10```
11
12
13## Usage
14
15```js
16const dotProp = require('dot-prop');
17
18// getter
19dotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar');
20//=> 'unicorn'
21
22dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep');
23//=> undefined
24
25dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep', 'default value');
26//=> 'default value'
27
28dotProp.get({foo: {'dot.dot': 'unicorn'}}, 'foo.dot\\.dot');
29//=> 'unicorn'
30
31// setter
32const obj = {foo: {bar: 'a'}};
33dotProp.set(obj, 'foo.bar', 'b');
34console.log(obj);
35//=> {foo: {bar: 'b'}}
36
37const foo = dotProp.set({}, 'foo.bar', 'c');
38console.log(foo);
39//=> {foo: {bar: 'c'}}
40
41dotProp.set(obj, 'foo.baz', 'x');
42console.log(obj);
43//=> {foo: {bar: 'b', baz: 'x'}}
44
45// has
46dotProp.has({foo: {bar: 'unicorn'}}, 'foo.bar');
47//=> true
48
49// deleter
50const obj = {foo: {bar: 'a'}};
51dotProp.delete(obj, 'foo.bar');
52console.log(obj);
53//=> {foo: {}}
54
55obj.foo.bar = {x: 'y', y: 'x'};
56dotProp.delete(obj, 'foo.bar.x');
57console.log(obj);
58//=> {foo: {bar: {y: 'x'}}}
59```
60
61
62## API
63
64### get(obj, path, [defaultValue])
65
66### set(obj, path, value)
67
68Returns the object.
69
70### has(obj, path)
71
72### delete(obj, path)
73
74#### obj
75
76Type: `Object`
77
78Object to get, set, or delete the `path` value.
79
80#### path
81
82Type: `string`
83
84Path of the property in the object, using `.` to separate each nested key.
85
86Use `\\.` if you have a `.` in the key.
87
88The following path components are invalid and results in `undefined` being returned: `__proto__`, `prototype`, `constructor`.
89
90#### value
91
92Type: `any`
93
94Value to set at `path`.
95
96#### defaultValue
97
98Type: `any`
99
100Default value.
101
102
103## License
104
105MIT © [Sindre Sorhus](https://sindresorhus.com)
106