Skip to content

Instantly share code, notes, and snippets.

@elcodabra
Created May 25, 2020 11:00
Show Gist options
  • Select an option

  • Save elcodabra/ac3212f154b946e161dd4346869df791 to your computer and use it in GitHub Desktop.

Select an option

Save elcodabra/ac3212f154b946e161dd4346869df791 to your computer and use it in GitHub Desktop.

Revisions

  1. elcodabra created this gist May 25, 2020.
    37 changes: 37 additions & 0 deletions utils__tests__objects.js
    Original 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)
    })

    })
    17 changes: 17 additions & 0 deletions utils_objects.js
    Original 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
    }