getPropByPath:根据字符串路径获取对象属性 : 'obj[0].count'

function getPropByPath(obj, path, strict) {      
  let tempObj = obj;

  path = path.replace(/\[(\w+)\]/g, '.$1'); //将[0]转化为.0

  path = path.replace(/^\./, ''); //去除开头的.


  let keyArr = path.split('.'); //根据.切割

  let i = 0;

  for (let len = keyArr.length; i < len - 1; ++i) {

    if (!tempObj && !strict) break;

      let key = keyArr[i];

    if (key in tempObj) {

      tempObj = tempObj[key];

    } else {

      if (strict) {//开启严格模式,没找到对应key值,抛出错误

        throw new Error('please transfer a valid prop path to form item!');

      }

      break;

    }

  }

  return {

    o: tempObj, //原始数据

    k: keyArr[i], //key值

    v: tempObj ? tempObj[keyArr[i]] : null // key值对应的值

  };
};
posted @ 2020-01-19 15:23  入坑的H  阅读(620)  评论(0编辑  收藏  举报