Last active
April 22, 2019 09:20
-
-
Save ohcrfpv/8eec9fcbeabb192a5148a9f28f7881e2 to your computer and use it in GitHub Desktop.
js 递归函数 获取json
This file contains 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
function fetchLast(obj, strs) { | |
// 1 | |
// obj = a | |
// strs = ['b', 'c', 'd'] | |
// 2 | |
// obj = a['b'] | |
// strs = ['c', 'd'] | |
// 3 | |
// obj = a['b']['c'] | |
// strs = ['d'] | |
var tempStr = strs[0]; | |
var tempObj = obj[tempStr]; | |
// Underscore.js | |
var tempStrs = _.clone(strs); | |
// 1 | |
// tempStr = 'b' | |
// tempObj = a['b'] | |
// 2 | |
// tempStr = 'c' | |
// tempObj = a['b']['c'] | |
// 3 | |
// tempStr = 'd' | |
// tempObj = a['b']['c']['d'] | |
if (tempStrs.length === 1) { | |
// tempObj = a['b']['c']['d'] | |
return tempObj; | |
} | |
tempStr.shift(); | |
// 1 | |
// tempObj = a['b'] | |
// tempStr = ['c', 'd'] | |
// 2 | |
// tempObj = a['b']['c'] | |
// tempStr = ['d'] | |
return fetchLast(tempObj, tempStrs); | |
} | |
function safeFetchJsonArray(args...) { | |
var rs = []; | |
try { | |
let obj = args? args[0]: {}; | |
let strs = _.clone(args); | |
strs.shift(); | |
// obj = a | |
// strs = ['b', 'c', 'd'] | |
rs = fetchLast(obj, strs); | |
} catch (e) { | |
console.log(e); | |
rs = []; | |
} finally { | |
return rs; | |
} | |
} | |
var a = { | |
b: { | |
c: { | |
d: ['ddddd'] | |
} | |
} | |
} | |
var d = safeFetchJsonArray(a, 'b', 'c', 'd') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment