@alexbinary/object-deep-assign

1.0.11 • Public • Published

object-deep-assign

Like Object.assign() but deep 😱

npm GitHub release Build Status dependencies Status devDependencies Status

Ever needed to do Object.assign() but couldn't because you had nested objects that got overwritten instead of merged ?

object-deep-assign merges objects recursively and can work with any depth. It has an API similar to Object.assign().

object-deep-assign comes handy when you need to deal with e.g. configuration objects when you have a layered config system (e.g. a default, global and local config).

Example

let objectDeepAssign = require('@alexbinary/object-deep-assign')

let defaultConf = {
  build: true,
  notify: {
    on_success: false,
    on_failure: true,
    options: {
      admin_only: true
      retry: 1
    }
  }
}

let globalConf = {
  notify: {
    on_success: true
    options: {
      retry: 2
    }
  }
}

let userConf = {
  notify: {
    options:
      admin_only: false
      retry: 3
  },
  deploy: true
}

let finalConf = objectDeepAssign({}, defaultConf, globalConf, userConf)
// finalConf = {
//   build: true,
//   deploy: true,
//   notify: {
//     on_success: true,
//     on_failure: true,
//     options: {
//       admin_only: false,
//       retry: 3
//     }
//   }
// }

Motivation

I wanted to try and write this thing myself, with the simplest code possible.

Compatibility

The code is written in plain ES2015, so it does not run on node before version 6.

Install

Install with npm or yarn :

$ npm install @alexbinary/object-deep-assign
# or
$ yarn add @alexbinary/object-deep-assign

Documentation

let objectDeepAssign = require('@alexbinary/object-deep-assign')

objectDeepAssign(target, ...sources)

Copies properties of sources onto target.

Scalar properties with same name are replaced. Object properties are merged recursively. Sources are merged sequentially into target from left to right.

Returns target.

Tests

Tests are written with mocha and chai. To run the tests first do :

$ npm install  # or `yarn`

to install the dev dependencies, and then do :

$ npm test  # or `yarn test`

To run the test in watch mode do :

$ npm testw # or `yarn testw`

Contributions

Contributions are welcome, feel free to open issues and submit pull requests on GitHub !

Related

Licence

MIT

Package Sidebar

Install

npm i @alexbinary/object-deep-assign

Weekly Downloads

4

Version

1.0.11

License

MIT

Last publish

Collaborators

  • alexbinary