Skip to content

Commit

Permalink
feat: add object utils
Browse files Browse the repository at this point in the history
  • Loading branch information
fupengl committed Sep 4, 2021
1 parent 8082850 commit 7da6d2a
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/object/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ export { default as flipObject } from './flip-object';
export { default as convertObjectKeysCase } from './convert-object-keys-case';
export { default as createDict } from './create-dict';
export { default as copyDict } from './copy-dict';
export { default as toPlanObject } from './to-plan-object';
export { default as toObjectArray } from './to-object-array';
41 changes: 41 additions & 0 deletions src/object/to-object-array.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import type { Dictionary } from '../type';

type ToObjectArrayOptions = {
/**
* @default value
*/
keyPropName?: string;
/**
* @default label
*/
valuePropName?: string;
};

/**
* object to array
* @param dict {Dictionary<any>}
* @param opts {ToObjectArrayOptions}
* @default { keyPropName: 'label', valuePropName: 'value' }
* @example
* ```ts
* const a = { a: 1, b: 2 }
* toObjectArray(a) // [{ value: 'a', label: 1 }, { value: 'b', label: 2 }]
* ```
* @category Object
*/
function toObjectArray<T extends Record<string, any> = { label: any; value: string }>(
dict: Dictionary<any>,
opts?: ToObjectArrayOptions,
): Array<T> {
const { keyPropName = 'value', valuePropName = 'label' } = opts || {};
const result: any[] = [];
for (const k in dict) {
result.push({
[keyPropName]: k,
[valuePropName]: dict[k],
});
}
return result;
}

export default toObjectArray;
15 changes: 15 additions & 0 deletions src/object/to-plan-object.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* 转换成对象
* @param value
* @category Object
*/
function toPlanObject(value?: any): Object {
value = Object(value);
const result = {};
for (const k in value) {
result[k] = value[k];
}
return result;
}

export default toPlanObject;

0 comments on commit 7da6d2a

Please sign in to comment.