Home

Awesome

set-nested-prop

package version package downloads standard-readme compliant package license make a pull request

Set nested object property (supports custom seperator, mutation, forcing creation & multi set)

Table of Contents

Install

This project uses node and npm.

$ npm install set-nested-prop
$ # OR
$ yarn add set-nested-prop

Usage

import set from 'set-nested-prop'

// By default the original object is not modified and . is used as a seperator

const obj1 = {
  foo: {
    bar: {
      baz: 5
    }
  }
}

const newObj = set(obj1, 'foo.bar.baz', 6)
console.log(newObj) // { foo: { bar: { baz: 6 } } }
console.log(obj1) // { foo: { bar: { baz: 5 } } }

// You can opt in for mutating
const obj2 = {
  foo: 5
}

set(obj2, 'foo', 6, { mut: true })
console.log(obj2.foo) // 6

// A custom seperator can be used

const customObj = set(obj1, 'foo*bar*baz', 7, { sep: '*' })
console.log(customObj) // { foo: { bar: { baz: 7 } } }

const forceObj = {}
const forceObjResult = set(forceObj, 'foo.bar', 1, {force: true})
console.log(forceObjResult) // {foo: {bar: 1}}

Contribute

  1. Fork it and create your feature branch: git checkout -b my-new-feature
  2. Commit your changes: git commit -am 'Add some feature'
  3. Push to the branch: git push origin my-new-feature
  4. Submit a pull request

License

MIT