From 557557f9d2625a9b9c8860decb6690290dfaa79d Mon Sep 17 00:00:00 2001 From: chengpeiquan Date: Sun, 19 Feb 2023 20:03:07 +0800 Subject: [PATCH] feat(utils): add excludeFields --- packages/utils/src/format.ts | 23 ++++++++++++++++++++- packages/utils/test/format.spec.ts | 32 ++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/packages/utils/src/format.ts b/packages/utils/src/format.ts index f1f99e7..c95353d 100644 --- a/packages/utils/src/format.ts +++ b/packages/utils/src/format.ts @@ -1,4 +1,4 @@ -import { isObject } from './data' +import { hasKey, isObject } from './data' /** * Extract numbers from text @@ -180,3 +180,24 @@ export function unique({ primaryKey, list }: UniqueOptions): T[] { return uniqueList } + +/** + * Exclude specified fields from the object + * @tips Only handle first-level fields + * @param object - An object as data source + * @param fields - Field names to exclude + * @returns A processed new object + * + * @category format + */ +export function excludeFields(object: Record, fields: string[]) { + if (!isObject) return object + + const newObject: Record = {} + for (const key in object) { + if (hasKey(object, key) && !fields.includes(key)) { + newObject[key] = object[key] + } + } + return newObject +} diff --git a/packages/utils/test/format.spec.ts b/packages/utils/test/format.spec.ts index a47872a..377810d 100644 --- a/packages/utils/test/format.spec.ts +++ b/packages/utils/test/format.spec.ts @@ -10,6 +10,7 @@ import { escapeRegExp, sortKeys, unique, + excludeFields, } from '..' describe('format', () => { @@ -159,4 +160,35 @@ describe('format', () => { { foo: 3, bar: [1, 2, 3] }, ]) }) + + it('excludeFields', () => { + const obj = { + foo: 'foo', + bar: 'bar', + baz: { + foo: 'foo', + bar: 'bar', + }, + num: 1, + bool: true, + } + + expect(excludeFields(obj, ['foo', 'bar'])).toEqual({ + baz: { + foo: 'foo', + bar: 'bar', + }, + num: 1, + bool: true, + }) + + expect(excludeFields(obj, ['baz', 'num'])).toEqual({ + foo: 'foo', + bar: 'bar', + bool: true, + }) + + expect(excludeFields(obj, [])).toEqual(obj) + expect(excludeFields(obj, ['test'])).toEqual(obj) + }) })