- Gets an object containing value and search feedback info matching a property path.
- Recognizes negative array indexing.
Name: get-property
Install:
npm i -S @webkrafters/get-property
npm insall -save-dev @webkrafters/get-property
import getProperties from '@webkrafters/get-property';
const property = getProperties(data, path, defaultValue?); // => PropertyInfo
NAME | DESCRIPTION | TYPE | DEFAULT | |
---|---|---|---|---|
1. | source | Data containing the property searched. | Any | N.A. |
2. | path |
Property path to search e.g.'friends.-3.name.last' ,'friends.[-3].name.last' ,['friends', -3, 'name', 'last'] Negative indexes are allowed. |
Integer String Symbol Array<Integer|String|Symbol> |
N.A. |
3. |
defaultValue [optional] |
Value property to return if data at property path is either not found or null or undefined .
|
Any | Undefined |
NAME | DESCRIPTION | TYPE | |
---|---|---|---|
1. | _value |
Actual value found at the property path. It is undefined if none found.
|
Any |
2. | exists | True if property path found. | Boolean |
3. | index | Sanitized key corresponding to an index if the parent is an array and and the current key is alphanumeric integer. | Integer |
4. | isSelf |
True if property path is pointing at the source argument. This occurs when path argument is either undefined or an empty array.
|
Boolean |
5. | key |
The final key in the path argument list.
|
Integer String Symbol |
6. | source |
Reference to the node within the source argument containing the property data. Will be undefined if property was not found.
|
Array Object |
7. | trail | Property path segment representing the farthest valid property/sub property path found. | Array<Integer|String|Symbol> |
8. | value |
Value returned. May contain defaultValue if found value is either not found or null or undefined
|
Any |
import getProperties from '@webkrafters/get-property';
const source = {
address: {
city: 'Test City',
state: 'My Province'
},
matrix: [
[ [ 0, 3, 1 ], [ 4, 0, 3 ] ],
[ [ 4, 1, 9 ], [ 7, 4, 9 ] ],
[ [ 8, 7, 3 ], [ 0, 3, 1 ] ]
],
registered: {
time: new Date(),
timezone: 'Eastern Time'
},
tags: [ 'test', 'foo', 'bar', 'baz', 'boo', 'tap', 'bak' ]
};
const property = getProperties(
source,
'registered.timezone',
'Mountain Time'
);
// returns property info object => {
// _value: 'Eastern Time',
// exists: true,
// index: NaN,
// isSelf: false,
// key: 'timezone',
// source: {
// time: new Date(),
// timezone: 'Eastern Time'
// },
// trail: [ 'registered', 'timezone' ],
// value: 'Eastern Time'
// }
// USING SAME SOURCE OBJECT AS ABOVE USAGE
// ---------------------------------------
const property = getProperties(
source,
'matrix[1][0][8]',
'n.a.'
);
// returns property info object => {
// _value: undefined,
// exists: false,
// index: 8,
// isSelf: false,
// key: '8',
// source: [ 4, 1, 9 ],
// trail: [ 'matrix', 1, 0 ],
// value: 'n.a.'
// }
MIT