类型转换
arrayToTree
数组转树结构
typescript
import { arrayToTree } from '@fang-kang/js-utils';
/**
* const { arr, idKey = 'id', parentKey = 'pid', childrenKey = 'children', rootId = 0 } = params;
*/
const arr = [
{ id: 1, name: '部门1', pid: 0 },
{ id: 2, name: '部门2', pid: 1 },
{ id: 3, name: '部门3', pid: 1 },
{ id: 4, name: '部门4', pid: 3 },
{ id: 5, name: '部门5', pid: 4 },
];
const tree = arrayToTree({ arr });
/**
* [
{
id: 1,
name: '部门1',
pid: 0,
children: [
{
id: 2,
name: '部门2',
pid: 1,
children: [],
},
{
id: 3,
name: '部门3',
pid: 1,
children: [
// 结果 ,,,
],
},
],
},
];
*/
base64ToBlob
base64 转 Blob 对象
typescript
import { base64ToBlob } from '@fang-kang/js-utils';
base64ToBlob('base64');
base64ToFile
base64 转 File 对象
typescript
import { base64ToFile } from '@fang-kang/js-utils';
base64ToFile('base64', '文件名');
blobToUrl
Blob 转为 url
typescript
import { blobToUrl } from '@fang-kang/js-utils';
blobToUrl(Blob);
fileToArrayBuffer
文件转 buffer
typescript
import { fileToArrayBuffer } from '@fang-kang/js-utils';
fileToArrayBuffer(File);
fileToBlob
File 文件转为 Blob
typescript
import { fileToBlob } from '@fang-kang/js-utils';
fileToBlob(File);
hexToRgb
hex 转 rgba
typescript
import { hexToRgb } from '@fang-kang/js-utils';
hexToRgb('#ffffff'); // rgb(255,255,255)
rgbToHex
rgb 转 Hex
typescript
import { rgbToHex } from '@fang-kang/js-utils';
rgbToHex('rgb(255,255,255)'); // #ffffff
toArray
如果是数组直接返回否则封装成数组
typescript
import { toArray } from '@fang-kang/js-utils';
toArray(1); // [1]
toNumber
转换成数字
typescript
import { toNumber } from '@fang-kang/js-utils';
toNumber('111'); // 111
byteToFileSize
将字节转换为合理的容量单位
typescript
import { byteToFileSize } from '@fang-kang/js-utils';
byteToFileSize(1024000000); // 976.6 MB
toAbsolutePath
将相对路径转换为绝对路径
typescript
import { toAbsolutePath } from '@fang-kang/js-utils';
toAbsolutePath('/a/b/c'); // http://localhost:8080/a/b/c
toBase64
将 url、File、Blob 类型转换为 base64
typescript
import { toBase64 } from '@fang-kang/js-utils';
const file = new File([''], 'test.png');
toBase64(file).then((res) => {
console.log(res); // data:image/png;base64,
});
toObject
将数组转换成对象
typescript
import { toObject } from '@fang-kang/js-utils';
/**
* @param { Array<any> } arr 数组
* @param { string[] = [] } filter 保留filter中的key
* @return { boolean }
*/
const arr = [
{
a: 1,
},
{
a: 3,
3: 5,
},
];
const data = toObject(arr, ['a']); // { a: [ 1, 3 ] }
toPxNum
将长度单位转换为数字
typescript
import { toPxNum } from '@fang-kang/js-utils';
toPxNum();