From 7da6d2a2e76f3db4cfb3da6ec2e908cf3080a176 Mon Sep 17 00:00:00 2001 From: fupeng Date: Sun, 5 Sep 2021 02:01:40 +0800 Subject: [PATCH] feat: add object utils --- src/object/index.ts | 2 ++ src/object/to-object-array.ts | 41 +++++++++++++++++++++++++++++++++++ src/object/to-plan-object.ts | 15 +++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 src/object/to-object-array.ts create mode 100644 src/object/to-plan-object.ts diff --git a/src/object/index.ts b/src/object/index.ts index 81ef7bc..bf57d0d 100644 --- a/src/object/index.ts +++ b/src/object/index.ts @@ -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'; diff --git a/src/object/to-object-array.ts b/src/object/to-object-array.ts new file mode 100644 index 0000000..f0b200c --- /dev/null +++ b/src/object/to-object-array.ts @@ -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} + * @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 = { label: any; value: string }>( + dict: Dictionary, + opts?: ToObjectArrayOptions, +): Array { + 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; diff --git a/src/object/to-plan-object.ts b/src/object/to-plan-object.ts new file mode 100644 index 0000000..508100a --- /dev/null +++ b/src/object/to-plan-object.ts @@ -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;