Skip to content

Commit

Permalink
feat(utils): add excludeFields
Browse files Browse the repository at this point in the history
  • Loading branch information
chengpeiquan committed Feb 19, 2023
1 parent 02e1645 commit 557557f
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
23 changes: 22 additions & 1 deletion packages/utils/src/format.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isObject } from './data'
import { hasKey, isObject } from './data'

/**
* Extract numbers from text
Expand Down Expand Up @@ -180,3 +180,24 @@ export function unique<T>({ primaryKey, list }: UniqueOptions<T>): 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<string, any>, fields: string[]) {
if (!isObject) return object

const newObject: Record<string, any> = {}
for (const key in object) {
if (hasKey(object, key) && !fields.includes(key)) {
newObject[key] = object[key]
}
}
return newObject
}
32 changes: 32 additions & 0 deletions packages/utils/test/format.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
escapeRegExp,
sortKeys,
unique,
excludeFields,
} from '..'

describe('format', () => {
Expand Down Expand Up @@ -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)
})
})

0 comments on commit 557557f

Please sign in to comment.