支持纯对象的obj
// isset.js module.exports = (obj, keyPath) => { const keys = keyPath.split('.'); for (const idx in keys) { if (Object.hasOwnProperty.call(obj, keys[idx])) { obj = obj[keys[idx]]; } else { return undefined; } } return obj; } // test.js const isset = require('./isset'); const config = { // 数据库配置 database: { sqlite: { dbname: 'order', path:'' }, }, // 上传配置 upload: { path: 'static/uploads/', } } console.log(isset(config, 'upload.path')); // 'static/uploads/' console.log(isset(config, 'upload.undef.path')); // undefined
这里为另一种实现,有点low,使用时自行斟酌
// isset.js /** * @description: 判断对象的key属性是否存在 * @param {string} key * @param {object} object * @return {boolean} */ export default function isset(key, object = {}){ key = 'object.'+key; try{ let _run= eval(key); if(_run === undefined){ return false; } // console.warn(key+':'+_run); return true; }catch(err){ // console.warn(key,err); return false; } }
调用:
// test.js import isset from './isset'; let obj = {config:[{thumbs:'...'}]} isset(`config[0].thumbs`, obj); // true isset(`config[0].other`, obj); // false