Last active
October 25, 2020 14:13
-
-
Save Reedef/f11ca4738966656960b963d7a7b04a1b to your computer and use it in GitHub Desktop.
链式获取数据
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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