Created
January 18, 2018 07:49
-
-
Save devCharles/663d694bba726345b3b85c2046a0217b to your computer and use it in GitHub Desktop.
a function to delete all unnecessary nested, or void data in a json recursivly
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 characters
const isPlainObject = require('lodash/isPlainObject') | |
const isString = require('lodash/isString') | |
const isNumber = require('lodash/isNumber') | |
const map = require('lodash/map') | |
const reduce = require('lodash/reduce') | |
function cleanObject (obj = {}) { | |
if (isNumber(obj)) return obj | |
if (isString(obj)) { | |
return (obj.trim().length === 0) ? null : obj | |
} | |
if (Array.isArray(obj)) { | |
if (obj.length === 0) return null | |
if (obj.length === 1) { | |
if (isString(obj[0])) { | |
return (obj[0] === '') | |
? null | |
: obj[0] | |
} else { | |
return cleanObject(obj[0]) | |
} | |
} | |
return map(obj, cleanObject) | |
} else if (isPlainObject(obj)) { | |
return reduce(obj, (acum, value, key) => { | |
return { | |
...acum, | |
[key]: cleanObject(value) | |
} | |
}, {}) | |
} | |
} | |
/* | |
Example | |
turns this: | |
{ | |
a: '', | |
b: 'string', | |
c: 123, | |
d: [''] | |
e: [ | |
{ | |
key: 'val', | |
blank: '', | |
nothing: [''] | |
} | |
], | |
f: [ | |
{ | |
aa: 'aa', | |
bb: 'bb' | |
}, | |
{ | |
aaa: 'aaa', | |
bbb: 'bbb' | |
} | |
] | |
} | |
Into this: | |
{ | |
a: null, | |
b: 'string', | |
c: 123, | |
d: null | |
e: { | |
key: 'val', | |
blank: null, | |
nothing: null | |
}, | |
f: [ | |
{ | |
aa: 'aa', | |
bb: 'bb' | |
}, | |
{ | |
aaa: 'aaa', | |
bbb: 'bbb' | |
} | |
] | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment