算法打卡day3——实现lodash的_.get()函数

32 阅读1分钟
//输入:
const obj = { 
          selector: { 
              to: { 
                  toutiao: "FE Coder"
              } 
          }, 
          target: [
              1, 
              2, 
              { 
                  name: 'byted'
              }
          ]
      };
      
get(obj, 'selector.to.toutiao', 'target[0]', 'target[2].name')

//输出:
['FE coder', 1, 'byted']
function get(obj,...path){
    return path.map((item) => {
        let temp = deep_copy(obj) //深拷贝一个新的obj
        item.replace(/\[/g,'.')
            .replace(/\]/g,'')
            .split('.')
            .map((key) => tmep && temp[key]) //防止temp为空报错
        return temp
    })
}


//深拷贝函数
function deep_copy(obj){
    if(typeof(obj) !== 'object' || obj == null){
        return obj
    }
    let newObj = Array.isArray(obj) ? [] : {}
    for(let key in obj){
        newObj[key] = deep_copy(obj[key])
    }
    return newObj
}