• Stars
    star
    571
  • Rank 78,127 (Top 2 %)
  • Language
    JavaScript
  • Created about 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Immutable version of dot-prop with some extensions

dot-prop-immutable

npm version Build Status CodeQL

Immutable version of dot-prop with some extensions.

npm install dot-prop-immutable

The motivation for this module is to have a simple utility for changing state in a React-Redux application without mutating the existing state of plain JavaScript objects. If you are going for real immutable data collections take a look at the cool library Immutable.js. A good practice is not to mix the immutable data collections with mutable objects because it can lead to confusion. Immutable objects are not accessed by the default semantics, but implemented by setters and getters.

This library implements 3 helper functions:

get(object, path) --> value
set(object, path, value) --> object
delete(object, path) --> object

None of the functions mutate the input object. For efficiency, the returned object is not a deep clone of the original, but a shallow copy of the objects in the mutated path.

Usage

const dotProp = require('dot-prop-immutable');
let state = { todos: [] }, index = 0;

// Add todo:
state = dotProp.set(state, 'todos', list => [...list, {text: 'cleanup', complete: false}])
// or with destructuring assignment
state = {...state, todos: [...state.todos, {text: 'cleanup', complete: false}]};
//=>  { todos: [{text: 'cleanup', complete: false}] }

// Complete todo:
state = dotProp.set(state, `todos.${index}.complete`, true)
// or with destructuring assignment
state = {...state, todos: [
	...state.todos.slice(0, index),
	{...state.todos[index], complete: true},
	...state.todos.slice(index + 1)
]};
//=>  { todos: [{text: 'cleanup', complete: true}] }

// Delete todo:
state = dotProp.delete(state, `todos.${index}`)
// or with destructuring assignment
state = {...state, todos: [
	...state.todos.slice(0, index),
	...state.todos.slice(index + 1)
]};
//=>  { todos: [] }

get

Access a nested property by a dot path

// Getter
dotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar')
//=> 'unicorn'

dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep')
//=> undefined

dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep', 'default value')
//=> default value

dotProp.get({foo: {'dot.dot': 'unicorn'}}, 'foo.dot\\.dot')
//=> 'unicorn'

or use a property array as a path.

// Use an array as get path
dotProp.get({foo: {'dot.dot': 'unicorn'}}, ['foo', 'dot.dot'])
//=> 'unicorn'

It is also possible to index into an array where the special index $end refers to the last element of the array.

const obj = {foo: [{ bar: 'gold-unicorn'}, 'white-unicorn', 'silver-unicorn']};

// Index into array
dotProp.get(obj, 'foo.1')
//=> 'white-unicorn'

dotProp.get(obj, 'foo.0.bar')
//=> 'gold-unicorn'

// Index into array with $end
dotProp.get(obj, 'foo.$end')
//=> 'silver-unicorn'

// If obj is an array
dotProp.get([{ bar: 'gold-unicorn'}, 'white-unicorn', 'silver-unicorn'], '0.bar')
//=> 'gold-unicorn'

set

Modify a nested property by a dot path

// Setter
const obj = {foo: {bar: 'a'}};

const obj1 = dotProp.set(obj, 'foo.bar', 'b');
//obj1 => {foo: {bar: 'b'}}

const obj2 = dotProp.set(obj1 , 'foo.baz', 'x');
//obj2 => {foo: {bar: 'b', baz: 'x'}}

where obj, obj1, obj2, obj3 all are different objects.

Use a function to modify the selected property, where first argument is the old value.

// Setter where value is a function (get and set current value)
dotProp.set({foo: {bar: 'a'}}, 'foo.bar', v => v + 'bc')
//=> {foo: {bar: 'abc'}}

Modify a nested array

const obj = {foo: [{ bar: 'gold-unicorn'}, 'white-unicorn', 'silver-unicorn']};

// Index into array
dotProp.set(obj, 'foo.1', 'platin-unicorn')
//=> {foo: [{bar: 'gold-unicorn'}, 'platin-unicorn', 'silver-unicorn']}

dotProp.set(obj, 'foo.0.bar', 'platin-unicorn')
//=> {foo: [{bar: 'platin-unicorn'}, 'white-unicorn', 'silver-unicorn']}

// Index into array with $end
dotProp.set(obj, 'foo.$end', 'platin-unicorn')
//=> {foo: [{ bar: 'gold-unicorn'}, 'white-unicorn', 'platin-unicorn']}

delete

Delete a nested property/array by a dot path

const obj = {foo: [{ bar: 'gold-unicorn'}, 'white-unicorn', 'silver-unicorn']};

// delete
dotProp.delete(obj, 'foo.$end');
//=> {foo: [{ bar: 'gold-unicorn'}, 'white-unicorn']}

dotProp.delete(obj, 'foo.0.bar');
//=> {foo: [{}, 'white-unicorn', 'silver-unicorn']}

toggle

Toggle a boolean a value by a dot path.

const obj = {foo: { bar: true } };

// toggle
dotProp.toggle(obj, 'foo.bar');
//=> {foo: { bar: false } }

merge

Merge a value by a dot path.

The target value must be an object, array, null, or undefined.

  • If target is an object, Object.assign({}, target, param) is used.
  • If target an array, target.concat(param) is used.
  • If target is null or undefined, the value is simply set.
const obj = {foo: { bar: {a:1, b:2 } };

// merge object
dotProp.merge(obj, 'foo.bar', {c:3} );
//=> {foo: { bar:{ a:1, b:2, c:3} } }

var arr = {foo: { bar: [1, 2] } };

// merge array
dotProp.merge(arr, 'foo.bar', [3, 4] );
//=> {foo: { bar:[1, 2, 3, 4 ] }

License

MIT

More Repositories

1

multifetch

Express middleware for performing internal batch requests
JavaScript
86
star
2

chai-subset

"containSubset" object properties matcher for Chai
JavaScript
82
star
3

safe-json-stringify

A wrapper for JSON.stringify that handles circular references and prevent defined getters from throwing errors.
JavaScript
56
star
4

ssh-private-key-buildpack

SSH private key configuration
Shell
55
star
5

mongopatch

MongoDB patching tool
JavaScript
37
star
6

debitoor-api-docs

Debitoor API documentation
23
star
7

express-timeout-handler

JavaScript
17
star
8

mongo-round

When using the MongoDB aggregation framework. This helper function helps you do rounding of numbers
JavaScript
17
star
9

heroku-buildpack-converter-fonts

Various fonts for heroku instances
Shell
15
star
10

nocms

"NO, You don't need a CMS"
JavaScript
14
star
11

teamcity-merge

Script for TeamCity - Lets TeamCity handle merging to master and closing github pull request
Shell
13
star
12

schemagic

JSON validation with schemas, and schema tools
JavaScript
13
star
13

node-debitoor

Thin request-like interface for easy access to the Debitoor REST API from node.js.
JavaScript
11
star
14

merge-sort-stream

Merge sort two input streams to one sorted stream
JavaScript
10
star
15

heroku-buildpack-npmrc

Shell
9
star
16

request-retry-stream

A simple wrapper for request for streaming responses, with retry capability on recoverable errors.
JavaScript
9
star
17

groom

Node module. JSON.parse(JSON.stringify(myObject)) and remove all nulls and empty strings
JavaScript
8
star
18

github-auth

Middleware for github based authorization.
JavaScript
8
star
19

ab-test-result

JavaScript
4
star
20

debitoor-oauth-sample

Simple client side HTML app that demonstrates how to integrate the OAuth 2.0 flow in your application.
HTML
4
star
21

tcmerge

A command line tool making merge to master through teamcity-merge script easier for the developer
Shell
3
star
22

api-doc

Create documentation for the API of an express app
JavaScript
3
star
23

cloudflare-zone

Syncronizes a zone bind file with Cloudflare
JavaScript
3
star
24

cnf

Configuration loader.
JavaScript
3
star
25

mongo-map

When using mongoDB aggregation framework, this helper lets you make a lookup in a JS-map
JavaScript
3
star
26

mocha-strict-dependencies

Mocha test, that checks that you have strict dependencies on your package.json, except of whitelisted
JavaScript
3
star
27

parse-dependencies

JavaScript
2
star
28

cdnbro

fallback for cdn assets
JavaScript
2
star
29

eslint-config-debitoor

ESLint configuration for Debitoor
JavaScript
2
star
30

jshint-teamcity-reporter

A teamcity reporter for JSHint
JavaScript
2
star
31

is-ok

Check if a HTTP response is successful
JavaScript
1
star
32

email-blacklist

List of commonly misspelled email domains
JavaScript
1
star
33

pug-lint-config-debitoor

Pug linting configuration for Debitoor
JavaScript
1
star
34

cipher

πŸ” Encrypt/decrypt objects
JavaScript
1
star
35

nodeversioncheck

Checks that you are running the correct node version and process.exit(1)'s if you are not
JavaScript
1
star
36

printify-util

HTML
1
star
37

circuit-breaker-request

Make http requests with retries, and a circuit-breaker group per node process. Scales back the load on micro-services when the micro-service has problems
JavaScript
1
star
38

httpsonly

Express middleware that redirects all http requests to https
JavaScript
1
star
39

mongoindex

Generare ensureIndex statements based on indexes read from a MongoDB database. Use it for copying indexes from one db to another. From production to development/staging for example
JavaScript
1
star