zoukankan      html  css  js  c++  java
  • 利用字符串路径获取对象集合的值

    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;
      }
    

      

  • 相关阅读:
    BOM和DOM
    js
    前端css
    html介绍
    线程锁&&信号量&&GIL&&线程定时器&&进程池与线程池&&协程
    对于数据库的操作以及配置
    string 迭代器
    递归
    python 操作mysql数据库
    Python编辑器IDLE傻瓜入门
  • 原文地址:https://www.cnblogs.com/caoke/p/8583348.html
Copyright © 2011-2022 走看看