Skip to content

Instantly share code, notes, and snippets.

@elcodabra
Created May 25, 2020 11:00
Show Gist options
  • Save elcodabra/ac3212f154b946e161dd4346869df791 to your computer and use it in GitHub Desktop.
Save elcodabra/ac3212f154b946e161dd4346869df791 to your computer and use it in GitHub Desktop.
Function clearObject
import { clearObject } from 'utils_objects'
describe('clearObject()', () => {
test('clearObject({ x: 1, y: 2, z: 0, r: null }) should return { x: 1, y: 2, z: 0 }', () => {
expect(clearObject({ x: 1, y: 2, z: 0, r: null })).toEqual({ x: 1, y: 2, z: 0 })
})
test('clearObject({ reciever: { id: 1, comment: null } }) should return { reciever: { id: 1 } }', () => {
expect(clearObject({ reciever: { id: 1, comment: null } })).toEqual({ reciever: { id: 1 } })
})
test('clearObject({ reciever: { id: 1, comment: "123" } }) should return { reciever: { id: 1, comment: "123" } }', () => {
expect(clearObject({ reciever: { id: 1, comment: "123" } })).toEqual({ reciever: { id: 1, comment: "123" } })
})
test('clearObject({ reciever: { id: 1, comment: "" } }) should return { reciever: { id: 1 } }', () => {
expect(clearObject({ reciever: { id: 1, comment: "" } })).toEqual({ reciever: { id: 1 } })
})
test('clearObject([1,2,3]) should return [1,2,3]', () => {
expect(clearObject([1,2,3])).toEqual([1,2,3])
})
test('clearObject({ items: [{ id: 1 }, { id: 2 }, { id: 3 } ] }) should return { items: [{ id: 1 }, { id: 2 }, { id: 3 } ] }', () => {
expect(clearObject({ items: [{ id: 1 }, { id: 2 }, { id: 3 } ] })).toEqual({ items: [{ id: 1 }, { id: 2 }, { id: 3 } ] })
})
test('clearObject({}) should return null', () => {
expect(clearObject({})).toBe(null)
})
test('clearObject([]) should return null', () => {
expect(clearObject([])).toBe(null)
})
})
const defaultIsMatchFn = val => val === null || val === undefined || val === ''
export function clearObject(obj, isMatchFn = defaultIsMatchFn) {
if (isMatchFn(obj)) return null
if (typeof obj === 'object') {
const initial = obj instanceof Array ? [] : {}
const result = Object.keys(obj).reduce((acc, key) => {
const value = clearObject(obj[key])
return Object.assign(initial, acc, defaultIsMatchFn(value) ? {} : { [key]: value })
}, initial)
return Object.keys(result).length ? result : null
}
return obj
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment