using JSON.stringify() with values that are not JSON safe

The .toJSON() method can be defined on an object to be use to transform the object when running JSON.stringify().

JavaScript

const includesUnsafeJSON = {
    favoriteWater: undefined,
    favoriteColors: ['red', 'green', 'blue'],
    multiplyByTwo(number) {
        return number * 2;
    }
};

includesUnsafeJSON.toJSON = function () {
    return {
        ...this
    };
};

JSON.stringify(includesUnsafeJSON);
// '{"favoriteColors":["red","green","blue"]}'

An optional second argument can be passed in to tell JSON.stringify() what properties to keep.

If an array is passed in it will only include the properties with the key values in the array.

JavaScript

const food = {
    fruits: ['apples', 'oranges'],
    vegetables: ['carrots', 'potatoes'],
    colors: ['red', 'green', 'blue']
};

JSON.stringify(food, ['fruits', 'vegetables']);
// '{"fruits":["apples","oranges"],"vegetables":["carrots","potatoes"]}'

If a function is passed in

JavaScript

const food = {
    fruits: ['apples', 'oranges'],
    vegetables: ['carrots', 'potatoes'],
    colors: ['red', 'green', 'blue'],
    numbers: [1, 2, 3, 4]
};

JSON.stringify(food, (key, value) => {
    if (key === 'numbers') {
        return undefined;
    }

    if (key !== 'colors') {
        return value;
    }
});
// '{"fruits":["apples","oranges"],"vegetables":["carrots","potatoes"]}'
javascript
testing for NaN

NaN, Not a Number, is returned when doing math operations with values that aren't numbers.

javascript
converting an object to a number

What happens when trying to convert an object to a number.