Categories
JavaScript Answers

How to hide certain values in output from JSON.stringify() with JavaScript?

Spread the love

Sometimes, we want to hide certain values in output from JSON.stringify() with JavaScript.

In this article, we’ll look at how to hide certain values in output from JSON.stringify() with JavaScript.

How to hide certain values in output from JSON.stringify() with JavaScript?

To hide certain values in output from JSON.stringify() with JavaScript, we call JSON.stringify with an array of property keys that we want to include with the returned JSON string.

For instance, we write

const x = {
  x: 0,
  y: 0,
  divID: "xyz",
  privateProperty1: "foo",
  privateProperty2: "bar",
};

const str = JSON.stringify(x, ["x", "y", "divID"]);

to call JSON.stringify with object x and an array of keys from x that we want to include in the returned JSON string.

As a result, str is '{"x":0,"y":0,"divID":"xyz"}'.

Conclusion

To hide certain values in output from JSON.stringify() with JavaScript, we call JSON.stringify with an array of property keys that we want to include with the returned JSON string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *