js判断对象任意深度的key属性是否存在,js的iset方法

方法一:

支持纯对象的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


posted @ 2022-07-07 17:06  FacingScreen  阅读(670)  评论(0编辑  收藏  举报