@ngha/nested-value
Version:
nestedValue the value at `path` of `object`
80 lines (74 loc) • 2.51 kB
JavaScript
import { Injectable, Pipe, NgModule } from '@angular/core';
class NestedValueService {
constructor() {
/**
* nestedValue the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param defaultValue The value returned for `undefined` resolved values.
* @example
*
* const object = { 'a': 'aa', 'b': [123, '456'], c: [{ d: '123', e: 'abc' }, { d: '456', e: 'def' }] };
*
* nestedValue(object, 'a')
* // => 'aa'
*
* nestedValue(object, 'b')
* // => [123 , '456']
*
* nestedValue(object, ['c[0].d'])
* // => '123'
*
* nestedValue(object, ['c', [1], 'e'])
* // => 'abc'
*
* nestedValue(object, ['c', [1], 'f'])
* // => undefine
*
* nestedValue(object, ['c', [3], 'f'], 'default')
* // => 'default'
*
*/
this.nestedValue = (object, path, defaultValue) => {
const travel = regexp => String.prototype.split
.call(path, regexp)
.filter(Boolean)
.reduce((res, key) => (res !== null && res !== undefined ? res[key] : res), object);
const result = travel(/[,[\]]+?/) || travel(/[,[\].]+?/);
return result === undefined || result === object ? defaultValue : result;
};
}
}
NestedValueService.decorators = [
{ type: Injectable }
];
class NestedValuePipe {
constructor(nestedValueService) {
this.nestedValueService = nestedValueService;
}
transform(object, path, defaultValue) {
return this.nestedValueService.nestedValue(object, path, defaultValue);
}
}
NestedValuePipe.decorators = [
{ type: Pipe, args: [{ name: 'nestedValue' },] }
];
NestedValuePipe.ctorParameters = () => [
{ type: NestedValueService }
];
class NestedValueModule {
}
NestedValueModule.decorators = [
{ type: NgModule, args: [{
declarations: [NestedValuePipe],
exports: [NestedValuePipe],
providers: [NestedValueService]
},] }
];
/**
* Generated bundle index. Do not edit.
*/
export { NestedValueModule, NestedValuePipe, NestedValueService };
//# sourceMappingURL=ngha-nested-value.js.map