zoukankan      html  css  js  c++  java
  • 实现lodash.get功能

    类似lodash.get可以按path来取对象的值,同时也支援预设值,如下:

    /**
     * Created by milo on 17/3/22.
     */
    
    function deepGet(object, path, defaultValue) {
        return (!Array.isArray(path) ? path.replace(/[/g, '.').replace(/]/g, '').split('.') : path)
                .reduce((o, k) => (o || {})[k], object) || defaultValue;
    }
    
    var obj = { 'a': [{ 'b': { 'c': 3 } }] };
    
    var result =deepGet(obj, 'a[0].b.c');
    console.log(result);
    // => 3
    
    result=deepGet(obj, ['a', '0', 'b', 'c']);
    console.log(result);
    // => 3
    
    result=deepGet(obj, 'a.b.c', 'default');
    console.log(result);
    // => 'default'

    结果:

  • 相关阅读:
    C#深复制和浅复制
    C#程序设计六大原则记录
    C#异步
    线程同步
    线程基础
    委托,事件
    XmlSerializer
    C#接口
    C#封装
    C#多态
  • 原文地址:https://www.cnblogs.com/milo-xie/p/6602031.html
Copyright © 2011-2022 走看看