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;
}
}
手写一个通过属性路径字符串修改/获取对应的值
最新推荐文章于 2024-05-21 18:11:13 发布