objectFormatPath
根据数据的路径进行转化,返回自定义路径的新数据,不支持对数组批量转化,需要时请使用dataFormatPath
方法。
用法
ts
import { objectFormatPath } from 'mortise-tenon-tool';
const obj = {
count: 3,
time: ['2021', '2024'],
c1: 1,
c2: 2,
option: { child: ['q', 'w'], name: 'n' },
o: 4,
};
objectFormatPath(obj, [
['count', 'num'], // 将count 改为 num
['time[0]', 'startTime'], // 将time[0] 改为 startTime
['time[1]', 'endTime'], // 将time[1] 改为 endTime
['time'], // 传入一个值,表示删除该字段
['c1', 'cAry[0]'], // 支持转为数组类型
['c2', 'cAry[1]'],
['option.child[0]', 'option.a'],
[['option', 'child', '1'], ['option', 'b']], // 支持多级路径
['option.child'],
], obj);
/**
* =>
* {
* num: 3,
* startTime: '2021',
* endTime: '2024',
* cAry: [1, 2],
* option: {a: 'q', b: 'w', name: 'n'},
* o: 4,
* }
*/
参数类型
ts
type SetWithCustomizer = (nsValue: any, key: string, nsObject: object) => any;
/** 数据路径 */
export type DataPath = string | string[];
/** 转化的配置项 */
export interface FormatPathOptions {
/** 是否保留原数据,当传入的数据与移值的数据一致时生效 (默认不保留) */
retain?: boolean;
/** 默认值 */
def?: unknown;
/** 自定义赋值 */
custom?: (value: any, index?: number) => any;
/** 自定义设置函数 */
customizer?: SetWithCustomizer;
}
/** 转化数据路径的参数类型 */
export type FormatPathParam = [DataPath, DataPath?, FormatPathOptions?];
export {};
ts
import { FormatPathParam } from '../types';
/**
* 将目标对象路径进行修改,返回自定义新数据或移植数据
* @param sourceData 原数据(不会影响修改到这个数据)
* @param formatParams 要修改数据路径,[旧路径,新路径,转化的配置项]
* @param grafData 移植数据,可将新的数据直接移植到这个数据中,如果传入的是原数据,会拷贝为新数据并默认删除旧路径的数据
* @returns 新数据或移植数据,如果移植数据传入的是原数据,会拷贝为新数据,防止直接修改原数据
*/
export declare function objectFormatPath<R extends object>(sourceData?: any, formatParams?: FormatPathParam[], grafData?: object): R;