Working with conditions in the replacer parameter of JSON in JavaScript

What's causing this inconsistency in results?

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); 

However, when using this code snippet:

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); 

I'm unable to pinpoint the differences. Could it be a syntax error or simply not working as intended?

Answer №1

First, the entire data is examined and then each individual key/value pair is processed. By first rejecting the data because it's not a number, the outcome becomes undefined. However, if you compare data to numbers, everything works smoothly.

const user = {
  id: 1,
  firstName: 'John',
  lastName: 'Doe',
  age: 30,
};

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

console.log(dataJSON); 

Answer №2

This explanation simplifies the concept:

If the value is a string, it will return undefined. Otherwise, it will return the original value, effectively removing strings.

On the other hand,

If the value is a number, it will be returned. Otherwise, it will yield undefined, eliminating non-numbers. Only plain numbers will remain as a result.

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

console.log(json);

You could also have intended to execute

If the value is a number, it will return undefined. Otherwise, it will return the current value, excluding numbers while preserving everything else.

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 if you wanted only non-number primitives removed,

If the value is an object or a number, it will be kept. Otherwise, it will be discarded, maintaining the integrity of the data.

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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting a JS string into HTML markup

I recently developed a basic web application to manage telnet connections with routers using Node.js, Express, and WebSockets. After establishing a connection, the terminal stream is transmitted through a websocket as UTF-8 strings. However, my current is ...

Is there a way to invoke a method in Jest Enzyme without using .simulate()?

During my unit testing for a React flight seat selection application using Jest/Enzyme, I encountered a scenario where I need to test a method within my class-based component that runs after a button is clicked. However, the button in question resides deep ...

Retrieving data from an anonymous function in AngularJS and outputting it as JSON or another value

Within the following code, I am utilizing a server method called "getUserNames()" that returns a JSON and then assigning it to the main.teamMembers variable. There is also a viewAll button included in a report that I am constructing, which triggers the met ...

What is the specific function of $('id').on('click', this.method.bind(this)) in this scenario?

Check out the app I'm talking about here: I am delving into the bind method in JavaScript to grasp its essence. Upon experimenting with it in the console, my interpretation is that bind produces a duplicate of the function, wherein "this" is tethere ...

Are there any other ways to transform the JSON response into a specialized Dart object?

As a newcomer to flutter and dart, I am currently developing an application that utilizes a nodejs backend with MongoDB as the database. While working on fetching data from flutter using the HTTP package, I realized that I need to convert the JSON response ...

Enabling CORs headers in Express continues to lead to errors

I have implemented the CORS code provided on http://enable-cors.org/ for express into my index.js file. /*these first five line direct from http://enable-cors.org/.com*/ app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); ...

How can I find the length of an array in Mongoose without using

This is the model I am currently working with: const postSchema = Schema( { author: { type: Schema.Types.ObjectId, ref: "User", }, likes: [{ type: Schema.Types.ObjectId, ref: "Like", },], ...

Tips for designing table rows with varying column lengths using CSS and JavaScript

I am facing an issue while populating my table with data from a list. Currently, the table cells are being filled from left to right, but I want them to be populated from top to bottom. Unfortunately, I am unsure how to achieve this using a list method. ...

How can I specify the array's length when using JSON.stringify in AngularJS?

I am looking to store form values in JSON to send via $http.post. One of the values, rooms, should be an array with a length determined by the selected value from md-select. The value of Adult should be included within each room entry. var data = { rooms: ...

We could not find the requested command: nodejs-backend

As part of my latest project, I wanted to create a custom package that could streamline the initial setup process by using the npx command. Previously, I had success with a similar package created with node.js and inquirer. When running the following comma ...

What is the best location to insert JavaScript from a website template into a Blazor project?

I recently set up a new Blazor WebAssembly project in Visual Studio 2019 and wanted to integrate a website template. After downloading the template, I am unsure where to place the accompanying JavaScript files. Currently, I have placed them within my inde ...

I am unable to get JQuery UI Dialog to open on my end

Coding in HTML: <button type="button" class="btn btn-success" style="margin-bottom:14px" id="btnAdd" onclick="modaladdedit('URLToMyController')"><i class="fa fa-plus"> Add New</i></button> HEAD Tag Setup: <link rel=" ...

Extracting data enclosed in double quotes from a JSON list retrieved through a curl request

I have been trying to access an online JSON file and download it, however, I am encountering difficulties in parsing the data. Specifically, I am looking to extract IP addresses that are enclosed within double quotes from the JSON file. While I can use jq ...

Modifying the appearance of a Component within a NavLink

I'm currently working on a navbar using NavLink from React-Router-Dom. It's fine to use the 'isActive' prop to style the active Link, but I'm stuck on how to style the subelements inside it. For more specific details, please take a ...

Tips for utilizing AJAX in Angular to load web pages in partials

My goal is to display a loader for each container while making an AJAX call to retrieve content. Initially, I want both div columns to show the loader, and then once the AJAX call is successful, I need to hide the loader for that specific column. Despite ...

Unexpectedly, the boolean variables are turning true without any apparent cause

var Number1 = 0 var Number2 = 0 var ZeroVAR = "0" var OneVAR = "1" var TwoVAR = "2" var ThreeVAR = "3" var FourVAR = "4" var FiveVAR = "5" var SixVAR = "6" var SevenVAR = "7" var EightVAR = "8" var NineVAR = "9" var EquationN1 = 0 var EquationN2 = 0 var Ad ...

The alert message fails to show up after the initial click on the close button

Whenever I click the x button to dismiss an alert message (indicating wrong data input in a form), the next time the user checks the form and enters incorrect data again, the alert message does not reappear after closing the x button. Any suggestions on ho ...

Expanding the capabilities of the Google Fit API by implementing support for a variety of data

I have implemented the Google Fit API with multiple user scopes. How can I incorporate multiple data types for each data source? Is it possible to add this as a data source? { "dataStreamName":"MyDataSource", "type":&quo ...

Exploring ways to create fresh arrays derived from the original array

On our company website, we have a wide array of vehicles available for purchase. Among these vehicles, there is a specific group of vans with detailed information such as the model and value. {vanNumber: "7654628", vanDescription: "VW Campervan", value: { ...

Developing a designated section of the code with specialized roles for administrators and vendors in React JavaScript

I am in the process of creating a dashboard for both admins and vendors. Is it feasible to structure the code so that if an admin builds one part, they have that option, and if a vendor builds another part, they have their own set of options? However, I w ...