利用字符串路径获取对象集合的值

let obj={a:{c:21},b:2}

const path='a.c'

const val=hget(obj,path,'默认值')

没有值就返回默认值

//利用字符串路径获取对象集合的值 对象:result 路径:path 默认值:def
  function hget(result,path,def){
    var result = result || {};
    (path || '').split('.').forEach(function(key){
      if(key && (typeof result !== 'undefined')){
        result = result[key];
      }
    });
    if(typeof result === 'undefined'){
      return def;
    } else {
      return result;
    }
  }
  function hset(result,path, value){
    if(typeof value === 'undefined'){
      for(var k in path){
        this[k]=path[k];
      }
    } else {
      path = String(path || '').trim();
      if(path){
        var paths = path.split('.'),
          last = paths.pop(),
          data = result || {};
        paths.forEach(function(key){
          var type = typeof data[key];
          if(type === 'object'){
            data = data[key];
          } else if(type === 'undefined'){
            data = data[key] = {};
          } else {
            console.error('forbidden to set property[' + key + '] of [' + type + '] data');
          }
        });
        data[last] = value;
      }
    }
    return result;
  }

  

posted @ 2018-03-16 16:54  无工时代  阅读(289)  评论(0编辑  收藏  举报