Home > Enterprise >  (JavaScript) Condition in the replacer parameter in JSON
(JavaScript) Condition in the replacer parameter in JSON

Time:09-01

Why this gives me the properties:

const person = {
  id: 1,
  firstName: 'Jack',
  lastName: 'White',
  age: 25,
};

const json = JSON.stringify(person, (key, value) => typeof(value) == "string" ? undefined : value);

console.log(json); 

But this gives me 'undefined':

const person = {
  id: 1,
  firstName: 'Jack',
  lastName: 'White',
  age: 25,
};

const json = JSON.stringify(person, (key, value) => typeof(value) == "number" ? value : undefined);

console.log(json); 

Can't get the differences. Is there a syntax error or just can't works in this way?

CodePudding user response:

Because the entire object is evaluated first, and then each key/value pair. You are denying the object first, because it is not a number, so the whole thing is undefined. If you match objects and numbers, it works.

const person = {
  id: 1,
  firstName: 'Jack',
  lastName: 'White',
  age: 25,
};

const json = JSON.stringify(person, (key, value) => (typeof(value) == "number" || typeof(value) == "object") ? value : undefined);

console.log(json); 

CodePudding user response:

This means:

typeof(value) == "string" ? undefined : value

When a string is found, return undefined. Otherwise, return the original value. So, strings get removed.

This means:

typeof(value) == "number" ? value : undefined

When a number is found, return that number. Otherwise, return undefined. So, non-numbers get removed. The only value that would produce a result would be a plain number.

const json = JSON.stringify(3, (key, value) => typeof(value) == "number" ? value : undefined);

console.log(json);

Perhaps you meant to do

typeof value == "number" ? undefined : value

removing numbers, but keeping everything else as is.

const person = {
  id: 1,
  firstName: 'Jack',
  lastName: 'White',
  age: 25,
};

const json = JSON.stringify(person, (key, value) => typeof(value) == "number" ? undefined : value);

console.log(json); 

Or perhaps you meant to remove only non-number primitives.

typeof value === "object" || typeof value === 'number' ? value : undefined

const person = {
  id: 1,
  firstName: 'Jack',
  lastName: 'White',
  age: 25,
};

const json = JSON.stringify(person, (key, value) => typeof value === "object" || typeof value === 'number' ? value : undefined);

console.log(json);

  • Related