包括但不限于中间有一层的值是null或undefined,或者中间某层是数组,一个一个if下去感觉有点麻烦,而且字符串型要判断 ''、null、undefined
包括但不限于中间有一层的值是null或undefined,或者中间某层是数组,一个一个if下去感觉有点麻烦,而且字符串型要判断 ''、null、undefined
const isObject = (obj) => obj && typeof obj === 'object' ? true : false;
const untieObjPath = objPath =>
objPath && objPath.trim() ? objPath.split(/\.|\[|\]\./).slice(1) : null;
const invoker = (segs, obj) =>
segs.reduce((obj, prop) => isObject(obj) ? obj[prop] : null, obj);
const res = {
response_body: {
records: [
{ user: { id: 100000 } },
null,
{ user: { id: 0 } },
{ user: 'Boooroo' },
50000
]
}
}
for (const i in [...Array(5).keys()]) {
const objPath = `res.response_body.records[${i}].user.id`;
const segs = untieObjPath(objPath);
console.log(invoker(segs, res));
}
// result:
// 100000
// null
// 0
// null
// null
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答5.1k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决
有呀 可选链
const res = a?.b?.c?.d?.e
就是兼容性要求比较高
如果你是
babel7
以上 可以用插件支持@babel/plugin-proposal-optional-chaining