Skip to content

Instantly share code, notes, and snippets.

@Reedef
Last active October 25, 2020 14:13
Show Gist options
  • Save Reedef/f11ca4738966656960b963d7a7b04a1b to your computer and use it in GitHub Desktop.
Save Reedef/f11ca4738966656960b963d7a7b04a1b to your computer and use it in GitHub Desktop.
链式获取数据
const getValue = (obj, keyChain = '', defaultValue = undefined) => {
if (typeof keyChain !== 'string' || keyChain === '' || !obj) return defaultValue || false;
const check = (object, keyArr, hasNext = false) => {
return ['[object Null]', '[object Undefined]'].indexOf(Object.prototype.toString.call(object[keyArr[0]])) === -1
? keyArr[1]
? check(object[keyArr[0]], keyArr.slice(1))
: object[keyArr[0]]
: hasNext ? undefined : defaultValue;
};
if (keyChain.indexOf('|') !== -1) {
const queue = keyChain.split('|');
const len = queue.length;
for (let i = 0; i < len; i++) {
const result = check(obj, queue[i].split('.'), i < len - 1);
if (typeof result !== 'undefined' || i === len - 1) {
return result;
}
}
}
return check(obj, keyChain.split('.'));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment