value.js 2.36 KB

/**
 * 通过路径获取值
 * @param {Object} obj
 * @param {String} path
 * @param {Number} subIndex
 * @returns
 */
export const getValueByPath = (obj, path, subIndex) => {
  if (!obj || !path || path.constructor != String) {
    return null
  }
  if (!/^\w?.*[\w|\]]$/.test(path)) {
    return null
  }
  let pathAry = path.split('.')
  if (pathAry.length == 1) {
    return obj[path]
  } else if (pathAry.length > 1) {
    let ret = obj
    for (var i = 0; i < pathAry.length; i++) {
      const key = pathAry[i]
      const match = /^(\w+)\[(\d+)\]$/.exec(key)
      if (match) {
        ret = ret[match[1]][match[2]]
      } else if (ret && ret.constructor === Array) {
        let index = 0
        if (subIndex != null && subIndex != undefined) {
          let preIndex = Number.parseInt(subIndex)
          if (!isNaN(preIndex)) {
            index = preIndex
          }
        }
        ret = ret[index][key]
      } else {
        if (ret && ret[key]) {
          ret = ret[key]
        } else {
          ret = null
        }
      }
    }
    return ret
  }
  return null
}

/**
 * 通过路径设置对象中的属性
 * @param {Object} obj
 * @param {String} path
 * @param {Any} value
 * @param {Number} subIndex
 * @returns
 */
export const setValueByPath = (obj, path, value, subIndex) => {
  if (!obj || !path || path.constructor != String) {
    return
  }
  if (!/^\w?.*[\w|\]]$/.test(path)) {
    return
  }
  let pathAry = path.split('.')
  if (pathAry.length == 1) {
    obj[path] = value
  } else if (pathAry.length > 1) {
    let ret = obj
    for (var i = 0; i < pathAry.length; i++) {
      const key = pathAry[i]
      const match = /^(\w+)\[(\d+)\]$/.exec(key)
      if (i == pathAry.length - 1) {
        if (match) {
          ret[match[1]][match[2]] = value
        } else if (ret && ret.constructor === Array) {
          let index = 0
          if (subIndex != null && subIndex != undefined) {
            let preIndex = Number.parseInt(subIndex)
            if (!isNaN(preIndex)) {
              index = preIndex
            }
          }
          ret[index][key] = value
        } else {
          if (ret && ret[key] !== undefined) {
            ret[key] = value
          } else {
            ret = null
          }
        }
      } else {
        if (match) {
          ret = ret[match[1]][match[2]]
        } else {
          ret = ret[key]
        }
      }
    }
  }
}