How to pass a replacer function to JSON.stringify() to customize the serialization in JavaScript

1 Answer

0 votes
class User {
    constructor(username, age, userid, password) {
        this.userid = userid;
        this.username = username;
        this.age = age;
        this.password = password; // should not be serialized
    }
}

const user = new User(9382732, "A AI", 52, "ah@746Eo87R!");

const jsonString = JSON.stringify(user, (key, value) => {
    if (key === "password") {
        return undefined; // Exclude this key
    }
    return value;
});

console.log("JSON String:", jsonString);



/*
run:

JSON String: {"userid":52,"username":9382732,"age":"A AI"}

*/

 



answered Dec 7, 2025 by avibootz
...