Skip to content
This repository has been archived by the owner on Oct 21, 2020. It is now read-only.
/ field Public archive

Easily set and get values of a field in your JavaScript object.

License

Notifications You must be signed in to change notification settings

jprichardson/field

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

field

Easily get, set, stub values of a field in a JavaScript object.

Why?

I got tired of doing this:

var port = cfg && cfg.env && cfg.env.prod && cfg.env.prod.port

now...

var field = require('field')
var port = field.get(cfg, 'env.prod.port')

or if you prefer ":"...

var field = require('field')
var port = field.get(config, 'env:prod:port')

I also got tired of writing long stubs:

var stub = {
  window: {
    localStorage: {
      getItem: function () {
        return 'data'
      },
      length: 1
    }
  }
}

now...

var field = require('field')
var stub = {}
field(stub, 'window:localStorage.getItem', function () { return 'data' })
field(stub, 'window:localStorage.length', 1)

Installation

npm i --save field

Usage

get

Gets the property value of the object. Returns undefined if it does not exist.

var field = require('field')
var dbPort = field.get(config, 'environment:production:port')

set

Sets the property value of the object. Returns the old value. If the field does not exist then it returns undefined and creates the object chain and sets the value.

var field = require('field')
var database = {}

console.log(field.get(database, 'production.port'))
// => undefined

// will return undefined since it never existed before
field.set(database, 'production.port', 27017)
console.log(database.production.port)
// => 27017

Binding

var field = require('field')

var bigObject = {
  host: {
    url: 'http://myserver.com'
  }
  /*
    ... some big object ...
  */
};

bigObject.get = field.get.bind(bigObject)
bigObject.set = field.set.bind(bigObject)

console.log(bigObject.get('host.url'))
// => 'http://myserver.com'

License

(MIT License)

Copyright 2015, JP Richardson

About

Easily set and get values of a field in your JavaScript object.

Resources

License

Stars

Watchers

Forks

Packages