Created
May 25, 2020 11:00
-
-
Save elcodabra/ac3212f154b946e161dd4346869df791 to your computer and use it in GitHub Desktop.
Revisions
-
elcodabra created this gist
May 25, 2020 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,37 @@ 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) }) }) This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,17 @@ 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 }