Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active March 28, 2021 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpivo/811e815493ec47d7e4d4815c105667fe to your computer and use it in GitHub Desktop.
Save rpivo/811e815493ec47d7e4d4815c105667fe to your computer and use it in GitHub Desktop.
Filtering Out Keys in an Object Using Json.Parse & json.stringify

Filtering Out Keys in an Object Using JSON.parse & JSON.stringify

The examples below make use of JSON.parse's second argument (aka the reviver) and JSON.stringify's second argument (aka the replacer).

Keep Only Specific Top-Level Keys

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

Filter Out Falsy Values (including Nested Values)

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 ] }
}
*/

Filter Out Specific Values (including Nested Values)

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 ] }
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment