ype dlvType = {
obj: object;
key: string;
def?: string;
p?: string;
undef?: string;
}
export function dlv(obj, key, def = '', undef = '') {
key = key.split ? key.split('.') : key;
for (let p = 0; p < key.length; p++) {
obj = obj ? obj[key[p]] : undef;
}
return obj === undef ? def : obj;
}
export function delve(obj, key, def = '', undef = '') {
return dlv(obj, key, def, undef);
}
How to use it
let obj = {
title: 'test',
a: {
b: {
c: 1,
d: undefined,
e: null
}
}
};
const title = delve(obj, 'title');
delve(obj, 'a.b.c') === 1;
delve(obj, ['a', 'b', 'c']) === 1;
delve(obj, 'a.b') === obj.a.b;
delve(obj, 'a.b.f') === undefined;
delve(obj, 'a.b.f', 'foo') === 'foo';
delve(obj, 'a.b.d', 'foo') === 'foo';
delve(obj, 'a.b.e', 'foo') === null;
delve(undefined, 'a.b.c') === undefined;
delve(undefined, 'a.b.c', 'foo') === 'foo';
delve(obj, undefined, 'foo') === 'foo';