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
|
16 | const dotProp = require('dot-prop');
|
17 |
|
18 | // getter
|
19 | dotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar');
|
20 | //=> 'unicorn'
|
21 |
|
22 | dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep');
|
23 | //=> undefined
|
24 |
|
25 | dotProp.get({foo: {'dot.dot': 'unicorn'}}, 'foo.dot\\.dot');
|
26 | //=> 'unicorn'
|
27 |
|
28 | // setter
|
29 | const obj = {foo: {bar: 'a'}};
|
30 | dotProp.set(obj, 'foo.bar', 'b');
|
31 | console.log(obj);
|
32 | //=> {foo: {bar: 'b'}}
|
33 |
|
34 | dotProp.set(obj, 'foo.baz', 'x');
|
35 | console.log(obj);
|
36 | //=> {foo: {bar: 'b', baz: 'x'}}
|
37 |
|
38 | // deleter
|
39 | const obj = {foo: {bar: 'a'}};
|
40 | dotProp.delete(obj, 'foo.bar');
|
41 | console.log(obj);
|
42 | //=> {foo: {}}
|
43 |
|
44 | obj.foo.bar = {x: 'y', y: 'x'};
|
45 | dotProp.delete(obj, 'foo.bar.x');
|
46 | console.log(obj);
|
47 | //=> {foo: {bar: {y: 'x'}}}
|
48 | ```
|
49 |
|
50 |
|
51 | ## API
|
52 |
|
53 | ### get(obj, path)
|
54 |
|
55 | ### set(obj, path, value)
|
56 |
|
57 | ### delete(obj, path)
|
58 |
|
59 | #### obj
|
60 |
|
61 | Type: `object`
|
62 |
|
63 | Object to get, set, or delete the `path` value.
|
64 |
|
65 | #### path
|
66 |
|
67 | Type: `string`
|
68 |
|
69 | Path of the property in the object. Use `.` for nested objects or `\\.` to add a `.` in a key.
|
70 |
|
71 | #### value
|
72 |
|
73 | Type: `any`
|
74 |
|
75 | Value to set at `path`.
|
76 |
|
77 |
|
78 | ## License
|
79 |
|
80 | MIT © [Sindre Sorhus](http://sindresorhus.com)
|