The examples below make use of JSON.parse
's second argument (aka the reviver) and JSON.stringify
's second argument (aka the replacer).
const obj = {
a: 1,
b: 2,
c: 3,
d: 'foo',
e: false,
f: null,
g: undefined,
}
console.log(
JSON.parse(
JSON.stringify(obj, ['a', 'c', 'e', 'g'])
)
)
// { a: 1, c: 3, e: false } <-- g won't be in the resulting object since it's undefined
const obj = {
a: 1,
b: 0,
c: 'foo',
d: false,
e: null,
f: undefined,
g: '',
h: [],
i: [null, undefined, 2, ''],
j: { a: '', b: 'b', c: 'c', d: false, e: null, f: undefined, g: [1,2,3] }
}
console.log(
JSON.parse(JSON.stringify(obj), (key, value) => value ? value : undefined)
)
/* returns
{
a: 1,
c: 'foo',
h: [],
i: [ <2 empty items>, 2, <1 empty item> ],
j: { b: 'b', c: 'c', g: [ 1, 2, 3 ] }
}
*/
const obj = {
a: 1,
b: 0,
c: 'foo',
d: false,
e: null,
f: undefined,
g: '',
h: [],
i: [null, undefined, 2, ''],
j: { a: '', b: 'b', c: 'c', d: false, e: null, f: undefined, g: [1,2,3] }
}
console.log(
JSON.parse(JSON.stringify(obj), (key, value) =>
// only filter out the value if it's either '' (empty string), null, or undefined.
['', null, undefined].includes(value) ? undefined : value
)
)
/* returns:
{
a: 1,
b: 0,
c: 'foo',
d: false,
h: [],
i: [ <2 empty items>, 2, <1 empty item> ],
j: { b: 'b', c: 'c', d: false, g: [ 1, 2, 3 ] }
}
*/