npm install --save object-path-operator
# or
yarn add object-path-operatorfunction getProp(obj: object, path: PropertyKey[]): unknownGet object property by path.
const obj = {
key: ['value']
}
getProp(obj, []) // throw error
getProp(obj, ['key', 0]) // value
getProp(obj, ['key-does-not-exist']) // throw errorfunction tryGetProp(obj: object, path: PropertyKey[], defaultValue?: unknown): unknownconst obj = {
key: ['value']
}
tryGetProp(obj, []) // undefined
tryGetProp(obj, ['key', 0]) // value
tryGetProp(obj, ['key-does-not-exist']) // undefinedfunction getOwnProp(obj: object, path: PropertyKey[]): unknownfunction tryGetOwnProp(obj: object, path: PropertyKey[], defaultValue?: unknown): unknownfunction setProp(obj: object, path: PropertyKey[], value: unknown): booleanSet object property by path.
const obj = {
key: ['value']
}
setProp(obj, [], 'new-value') // false
setProp(obj, ['key', 0], 'new-value') // true
setProp(obj, ['newKey'], 'new-value') // true
setProp(obj, ['path', 'does', 'not', 'exist'], 'new-value') // throw errorfunction trySetProp(
obj: object
, path: [PropertyKey, ...PropertyKey[]]
, value: unknown
): booleanconst obj = {
key: ['value']
}
trySetProp(obj, [], 'new-value') // false
trySetProp(obj, ['key', 0], 'new-value') // true
trySetProp(obj, ['newKey'], 'new-value') // true
trySetProp(obj, ['path', 'does', 'not', 'exist'], 'new-value') // falsefunction setOwnProp(obj: object, path: PropertyKey[], value: unknown): booleanfunction trySetOwnProp(obj: object, path: PropertyKey[], value: unknown): booleanfunction removeProp(obj: object, path: PropertyKey[]): booleanRemove object property by path.
const obj = {
key: ['value']
}
removeProp(obj, []) // throw error
removeProp(obj, ['key', 0]) // true
removeProp(obj, ['key-does-not-exist']) // throw errorfunction tryRemoveProp(obj: object, path: PropertyKey[]): booleanconst obj = {
key: ['value']
}
tryRemoveProp(obj, []) // false
tryRemoveProp(obj, ['key', 0]) // true
tryRemoveProp(obj, ['key-does-not-exist']) // falsefunction removeOwnProp(obj: object, path: PropertyKey[]): booleanfunction tryRemoveOwnProp(obj: object, path: PropertyKey[]): booleanfunction propExists(obj: object, path: PropertyKey[]): booleanconst obj = {
key: ['value']
}
propExists(obj, []) // throw error
propExists(obj, ['key', 0]) // true
propExists(obj, ['key-does-not-exist']) // falsefunction tryPropExists(obj: object, path: PropertyKey[]): booleanconst obj = {
key: ['value]
}
tryPropExists(obj, []) // false
tryPropExists(obj, ['key', 0]) // true
tryPropExists(obj, ['key-does-not-exist']) // falsefunction ownPropExists(obj: object, path: PropertyKey[]): booleanfunction tryOwnPropExists(obj: object, path: PropertyKey[]): boolean