$ npm i @chronocide/dot-obj
Note: This package requires Node >=10.12.0
get()
- Get property at any depthset()
- Set property at any depthsome()
- Test every property and returntrue
on first property that returnstrue
, otherwisefalse
every()
- Test every property and returnfalse
on first property that returnsfalse
, otherwisetrue
get<T>(object: Record<string, any>, path: string): T
Get property at any depth
Example
import dot from 'dot-obj';
// Get
dot.get({ foo: { bar: true } }, 'foo.bar') // => true
dot.get({ foo: { bar: true } }, 'foo.bar.baz') // => undefined
dot.get({ foo: { bar: true } }, 'bar') // => undefined
dot.get({ foo: [{ bar: true }, { baz: false }] }, 'foo.0') // => { bar: true }
// TS
dot.get<boolean>({ foo: { bar: true } }, 'foo.bar') // => true (boolean)
set<T extends Record<string, any>>(object: Record<string, any>, path: string, value: any): T
Set property at any depth
Example
import dot from 'dot-obj';
// Set
dot.set({ foo: { bar: true } }, 'foo', { baz: false }) // => { foo: { baz: false } }
dot.set({ foo: { bar: true } }, 'foo.bar', { baz: false }) // => { foo: { bar: { baz: false } } }
dot.set({ foo: { bar: true } }, 'baz', false) // => { foo: { bar: true }, baz: false }
// TS
dot.set<{ foo: { baz: false } }>({ foo: { bar: true } }, 'foo', { baz: false }) // => { foo: { baz: false } } ({ foo: { baz: false } })
some(object: Record<string, any>, match: (entries: [string, any]) => boolean): boolean
Test every property and return true
on first property that returns true
, otherwise false
import dot from 'dot-obj';
dot.some({ foo: { bar: true } }, ([key]) => key === 'foo') // true
dot.some({ foo: { bar: true } }, ([key]) => key === 'baz') // false
dot.some({ foo: { bar: true } }, ([, value]) => value === 'foo') // false
dot.some({ foo: { bar: true } }, ([, value]) => value === true) // true
every(object: Record<string, any>, match: (entries: [string, any]) => boolean): boolean
Test every property and return false
on first property that returns false
, otherwise true
import dot from 'dot-obj';
dot.every(
{ foo: { bar: true } },
([key]) => typeof key === 'string'
) // true
dot.every(
{ foo: { bar: true } },
([key]) => key === 'bar'
) // false
dot.every(
{ foo: { bar: true }, baz: true },
([key, value]) => key[0] === 'b' && value === true
) // true
dot.every(
{ foo: { bar: true } },
([, value]) => typeof value === 'boolean'
) // false