@ngha/nested-value
Version:
nestedValue the value at `path` of `object`
78 lines (61 loc) • 2.29 kB
Markdown
# nested-value
This library get object value by path
## Usage
Import `NestedValueModule` to your module
```ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app';
import { NestedValueModule } from '@ngha/nested-value';
export class AppModule {}
```
### nested-value
Returns value of an object value
**Usage:** `object | nestedValue: 'path' : 'defaultValue'`
```angular2html
<p>{{{ 'a': 'aa' } | nestedValue:'a'}}</p>
<!-- Output: "aa" -->
<p>{{{ c: [{ d: '123', e: 'abc' }, { d: '456', e: 'def' }] } | nestedValue:'c[0].d'}}</p>
<!-- Output: "123" -->
<p>{{{ c: [{ d: '123', e: 'abc' }, { d: '456', e: 'def' }] } | nestedValue:['c', [1], 'e']}}</p>
<!-- Output: "def" -->
<p>{{{ c: [{ d: '123', e: 'abc' }, { d: '456', e: 'def' }] } | nestedValue:['c', [3], 'f']: 'default'}}</p>
<!-- Output: "default" -->
<p>{{{ c: [{ d: '123', e: 'abc' }, { d: '456', e: 'def' }] } | nestedValue:['c', [3], 'f']}}</p>
<!-- Output: undefine -->
```
```typescript
import {NestedValueService} from '@ngha/nested-value'
export class AppComponent
{
constructor(private service: TransformObjectService)
{
const obj = {
aa: [{ b: { c: 0 }, 1: 0 }],
dd: { ee: { ff: 2 } },
gg: { h: 2 },
'gg.h': 1,
'kk.ll': { 'mm.n': [3, 4, { 'oo.p': 5 }, { 'oo': { p: 6 } }] },
tt: null
};
const result1 = this.service.nestedValue(obj , 'aa[0].b.c' ) === obj['aa'][0]['b']['c']
// Output: result1 = true
const result2 = this.service.nestedValue(obj , 'aa[0][1]') === obj['aa'][0][1]
// Output: result2 = true
const result3 = this.service.nestedValue(obj , ['kk.ll', 'mm.n', 2, 'oo.p']) === obj['kk.ll']['mm.n'][2]['oo.p']
// Output: result3 = true
const result4 = this.service.nestedValue(obj , ['kk.ll', 'mm.n', 3, 'oo', 'p']) === 6
// Output: result4 = true
const result5 = this.service.nestedValue(undefine , ['kk'] , 1) === 1
// Output: result5 = true
const result6 = this.service.nestedValue(undefine , 'kk') === undefine
// Output: result6 = true
}
}
```