手写一个通过属性路径字符串修改/获取对应的值

const regExp1 = new RegExp(eval(`\/^(?:[^\\[]+)\/`)); // 匹配abcd[0]或abcd中的abcd
const regExp2 = new RegExp(eval(`\/(?<=\\[)([^\\[\\]])*(?=\\])\/`), 'g');  // 匹配方括号中的内容,如:a['1']["5"][6]['abc']中的1、5、6、abc

// 通过路径获取对象某个属性的值
export function getValueByPropertyPath(target, propertyPath) {
  if (
    !target ||
    !propertyPath ||
    typeof target !== "object" ||
    typeof propertyPath !== "string"
  )
    return;
  let attrs = propertyPath.replace(/['|"]/g, '').split('.');
  let result = target;
  attrs.forEach(attr => {
    let matched2 = attr.match(regExp2);
    if (matched2) {
      let matched1 = attr.match(regExp1) || [];
      let matcheds = [...matched1, ...matched2];
      matcheds.forEach(key => {
        result = result[key];
      })
    } else {
      result = result[attr];
    }
  })
  return result;
}

// 通过路径设置对象某个属性的值
export function setValueByPropertyPath(target, propertyPath, value) {
  if (
    !target ||
    !propertyPath ||
    typeof target !== "object" ||
    typeof propertyPath !== "string"
  )
    return;
  let lastSecondPath = propertyPath.match(/(.*)(?=\.)/)[0];  // 匹配最后第二个路径
  let lastProperty = propertyPath.match(/(?<=\.)([^\.]*)$/)[0]; // 匹配最后的路径
  let lastSecondObj = getValueByPropertyPath(target, lastSecondPath);
  if (!lastSecondObj || typeof lastSecondObj !== 'object') return;
  lastProperty = lastProperty.replace(/['|"]/g, "");
  let result = lastSecondObj;
  let matched2 = lastProperty.match(regExp2);
  if (matched2) {
    let matched1 = lastProperty.match(regExp1) || [];
    let matcheds = [...matched1, ...matched2];
    matcheds.forEach((key, index) => {
      if (index === matcheds.length - 1) {
        result[key] = value;
      } else {
        result = result[key];
      }
    });
  } else {
    result[lastProperty] = value;
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值