Skip to content

Access and create object props safe and with confidence

Notifications You must be signed in to change notification settings

LuisPaGarcia/propx

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

38 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Safely accessing deeply nested values ⚡️

import { get, set } from "https://raw.githubusercontent.com/LuisPaGarcia/propx/master/mod.ts";

var obj = {
  child:{
    value: 1
  }
}

// get
console.log( get(obj, 'child.value') ) // 1
console.log( get(obj, 'child.value.nonexist') ) // undefined
console.log( get(obj, 'child.value.nonexist', "10") ) // 10

// set
console.log( set(obj, 'child.otherValue', ['hey']) )
// -> 
// {
//   child:{
//     value: 1,
//     otherValue: ['hey']
//   }
// }

For Node.js

  1. Install it using npm:
$ npm install propx 

or yarn:

$ yarn add propx 

Usage

// Using require
const { set, get } = require('propx');

// Using import (es6)
import { set, get } from 'propx';

// Target example
const obj = {
    a: 1,
    b: 2,
    c: { d: { e: { f: 3 } } },
    g: undefined
};

// How to use get
console.log(get(obj, 'c.d.e.f', ''))
//-> 3

// How to use set
console.log(set(obj, 'g.x.y.z', ['hey']))
/* -> {
    a: 1,
    b: 2,
    c: { d: { e: { f: 3 } } },
    g: { x: { y: { z: [ 'hey' ] } } }
}

*/

Definition

/**
 * @param {object} object base object to inject new prop
 * @param {string} path path to set the object
 * @param {any} value value to set
 */
function set(object: Object, path: string, value: any): Object {
    ...
}

/**
 *
 * @param {object} object object to access
 * @param { string | string[] } key string or array with dot notation path
 * @param { any } def optional parameter for default if the full key in path is missing
 */
function get(object: Object, key: string | string[], def: any) {
...
}

TODO:

  • Write tests
  • Use microbundle to generate module units.
  • Configure umd ussage for unpkg.com.

About

Access and create object props safe and with confidence

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published