safe-reaper
v2.1.0
Published
Retrieve property value by specifying an expression but without any null/undefined reference concern
Downloads
13
Readme
safe-reaper
Retrieve property value by specifying an expression but without any null/undefined reference concern
Install
npm
npm install --save safe-reaper
bower
bower install --save safe-reaper
Import
ES2015
import { reap } from 'safe-reaper'
CommonJS
const { reap } = require('safe-reaper')
script
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>DEMO</title>
</head>
<body>
<script type="text/javascript" src="node_modules/safe-reaper/dist/safereaper.js"></script>
<script type="text/javascript">
var reap = window.reap
</script>
</body>
</html>
Usage
reap(null, 'user.age') // undefined
reap(null, 'user.age', 38) // 38
const obj = {
user: {
name: 'HanMeimei'
}
}
reap<string>(obj, 'user.name') // Hanmeimei
reap<undefined>(obj, 'user.age') // undefined
reap<number>(obj, 'user.age', 33) // 33
reap<any>(obj, null, 33) // Error occurs
reap<string, string>(obj, 'user.name', '', val => `Hello ${val}`) // Hello HanMeimei
const users = [
{
name: 'LiLei'
}
]
reap<string>(users, '[0].name') // LiLei
reap<string>(users, '[0]["name"]') // LiLei
reap<number>(users, '[0]["age"]', 99) // 99
reap(source, pathExpression[, defaultValue, extraHandler])
source
: object you are going to usepathExpression
: the path leads to the result in specifyingsource
defaultValue
: will be used ifsource
isnull
/undefined
, or any intermediate value evaluated inpathExpression
extraHandler
: a function will be called to evaluate the final return
accept-expression
Dot notation - a
, a.b
, a.b.c
Bracket notation - a['b']
, a[0]
, a[0].c
, a[0]['c']
Hybrid - a.b[0]
, a[0].b