1.0.0 • Published 5 years ago
@dhirendra24/get-val v1.0.0
getVal
Get value from Object efficiently.
Getting value from Object is pretty simple in NodeJS, but the only thing annoy me is that it doesn't throw Error if the value is missing. I wrote a simple function that get the value and throw's an Error if value is missing.
Install
npm i @dhirendra24/get-val
Example
const getVal = require('@dhirendra24/get-val');
const mutedGetVal = require('@dhirendra24/get-val').mute();
const obj = {
'id': '0001',
'type': 'donut',
'name': 'Cake',
'ppu': 0.55,
'batters': {
'batter': [
{'id': '1001', 'type': 'Regular'},
{'id': '1002', 'type': 'Chocolate'},
{'id': '1003', 'type': 'Blueberry'},
{'id': '1004', 'type': 'Devil Food'}
]
}
};
getVal(obj, ['id']); // 0001
getVal(obj, ['batters', 'batter', 0]); // {'id': '1001', 'type': 'Regular'}
getVal(obj, ['batters', 'batter', 0, 'type']); // Regular
getVal(obj, ['unknown']); // Throws Error
getVal(obj, ['batters', 'batter', 10]); // Throws Error
getVal(obj, ['unknown'], 'default'); // default
mutedGetVal(obj, ['id']); // 0001
mutedGetVal(obj, ['batters', 'batter', 0]); // {'id': '1001', 'type': 'Regular'}
mutedGetVal(obj, ['batters', 'batter', 0, 'type']); // Regular
mutedGetVal(obj, ['unknown']); // undefined
mutedGetVal(obj, ['batters', 'batter', 10]); // undefined
mutedGetVal(obj, ['unknown'], 'default'); // default
Test
npm test
1.0.0
5 years ago