Skip to content

dataFormatPath

根据数据的路径进行转化,返回自定义路径的新数据,在objectFormatPath基础功能上扩展了对数组的批量修改的支持。

用法

ts
import type { FormatPathParam } from 'mortise-tenon-tool';
import { dataFormatPath } from 'mortise-tenon-tool';

const data = { a: [[1, 2], [3, 4]] };
const formatPaths: FormatPathParam[] = [
  ['a[][]', 'x[].y[].z'],
];

dataFormatPath(data, formatPaths);

/**
 * =>
 *  { x: [{ y: [{ z: 1 }, { z: 2 }] }, { y: [{ z: 3 }, { z: 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 dataFormatPath<R extends object>(sourceData?: any, formatParams?: FormatPathParam[], grafData?: object): R;

更多用例

测试用例

源码

源代码