Files
mayfly-go/frontend/src/common/utils/object.ts

121 lines
3.6 KiB
TypeScript
Raw Normal View History

/**
* 访
*
* @param obj {user: {name: 'xxx'}, orderNo: 1212211, products: [{id: 12}]}
* @param path 访 orderNo user.name product[0].id
* @returns
*/
export function getValueByPath(obj: any, path: string) {
const keys = path.split('.');
let result = obj;
for (let key of keys) {
if (!result) {
return undefined;
}
// 如果是字符串则尝试使用json解析
if (typeof result == 'string') {
try {
result = JSON.parse(result);
} catch (e) {
console.error(e);
return undefined;
}
}
if (typeof result !== 'object') {
return undefined;
}
if (key.includes('[') && key.includes(']')) {
// 处理包含数组索引的情况
const arrayKey = key.substring(0, key.indexOf('['));
const matchIndex = key.match(/\[(.*?)\]/);
if (!matchIndex) {
return undefined;
}
const index = parseInt(matchIndex[1]);
let arrValue = result[arrayKey];
if (typeof arrValue == 'string') {
try {
arrValue = JSON.parse(arrValue);
} catch (e) {
result = undefined;
break;
}
}
result = Array.isArray(arrValue) ? arrValue[index] : undefined;
} else {
result = result[key];
}
}
return result;
}
/**
*
* @param obj
* @param path
* @param value
*/
export function setValueByPath(obj: any, path: string[], value: any) {
for (let i = 0; i < path.length - 1; i++) {
const key = path[i];
if (!obj[key]) {
obj[key] = {};
}
obj = obj[key];
}
obj[path[path.length - 1]] = value;
}
/**
* 使
*
* @param obj
* @param callback
* @param hash WeakMap
* @returns
*/
export function deepClone(
obj: any,
callback: (key: string | number, value: any) => any = (key: string | number, value: any) => value,
hash = new WeakMap()
): any {
if (Object(obj) !== obj) return obj; // 基本数据类型直接返回
if (hash.has(obj)) return hash.get(obj); // 处理循环引用
let result: any;
if (obj instanceof Set) {
result = new Set();
hash.set(obj, result);
obj.forEach((val) => result.add(deepClone(val, callback, hash)));
} else if (obj instanceof Map) {
result = new Map();
hash.set(obj, result);
obj.forEach((val, key) => result.set(key, deepClone(val, callback, hash)));
} else if (obj instanceof Date) {
result = new Date(obj.getTime());
} else if (obj instanceof RegExp) {
result = new RegExp(obj);
} else if (typeof obj === 'object') {
result = Array.isArray(obj) ? [] : {};
hash.set(obj, result);
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
let value = obj[key];
value = callback(key, value);
result[key] = deepClone(value, callback, hash);
}
}
} else {
result = obj;
}
return result;
}