Skip to content

Instantly share code, notes, and snippets.

@ohcrider
Last active April 22, 2019 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohcrider/8eec9fcbeabb192a5148a9f28f7881e2 to your computer and use it in GitHub Desktop.
Save ohcrider/8eec9fcbeabb192a5148a9f28f7881e2 to your computer and use it in GitHub Desktop.
js 递归函数 获取json
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