Ways to eliminate nested properties in JSON.stringify()

Looking to make alterations to a string using Typescript. The string is generated by the JSON.stringify() function.

I aim to eliminate the attributes "id", "lightStatus", and "value" from both "inputPort" and "outputPort" objects, only keeping their respective "id" property.

console.log(JSON.stringify(this.light));
// Output -> {"id":1,"name":"Light Switch","lightStatus":true,"inputPort":{"id":2,"value":0},"outputPort":{"id":2,"value":false},"resistance":100}

I attempted the following method but encountered issues with "inputPort.id" and "outputPort.id". Below is my attempt and the resultant output:

var savedLight = JSON.stringify(this.light, ["name", "inputPort.id", "outputPort.id", "resistance"]);
// Output -> {"name":"Light Switch","resistance":100}

The desired outcome should consist of the properties "name", "inputPort id", "outputPort id", and "resistance". Like so:

{"name":"Light Switch","inputPort": 2, "outputPort": 2, "resistance":100}

Could use some assistance in removing the unnecessary properties. Any help would be appreciated.

Answer №1

One way to customize the output of JSON.stringify is by using a "replacer" function.

var data = {"id":1,"name":"Light Switch","lightStatus":true,"inputPort":{"id":2,"value":0},"outputPort":{"id":2,"value":false},"resistance":100};

var result = JSON.stringify(data, function(k, v) {
    switch (k) {
    case "": case "name": case "resistance":
        return v;
    case "inputPort": case "outputPort":
        return v.id;
    default:
        return undefined;
  }
}, 2)

document.querySelector("pre").textContent = result
<pre></pre>

The "" denotes the top-level object in the JSON. It keeps the original values for properties like "name" and "resistance".

For properties like "inputPort" and "outputPort", it only includes the id value.

All other properties are set to undefined, effectively excluding them from the final result.

Answer №2

To achieve this, you can implement a replacer function.

var object = {
  "id": 1,
  "name": "Light Switch",
  "lightStatus": true,
  "inputPort": {
    "id": 2,
    "value": 0
  },
  "outputPort": {
    "id": 2,
    "value": false
  },
  "resistance": 100
};

var stringifyOutput = JSON.stringify(object, function(key, value) {
  if (key === 'id' || key === 'lightStatus') {
    return void(0);
  }
  if (key === 'inputPort' || key === 'outputPort') {
    return value.id;
  }
  return value;
});

console.log(stringifyOutput);

Answer №3

If you want to modify the content of a JSON object before stringifying it, you can use the Replacer function within the JSON.stringify method.

var data='{"id":1,"name":"Light Switch","lightStatus":true,"inputPort":{"id":2,"value":0},"outputPort":{"id":2,"value":false},"resistance":100}';
var json=JSON.parse(data);

function replacer(key, value) {
  switch (key) {
    case "": case "name": case "resistance":
        return value;
    case "inputPort": case "outputPort":
        return value.id;
    default:
        return undefined;
  }
}

console.log(JSON.stringify(json, replacer));

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

Executing npm variables dynamically (such as process.env.SERVER) on a Windows system with Cmder - a step-by-step guide

I've put together a NodeJs, Selenium, and WebdriverIO framework, but I'm having trouble with running npm variables at runtime (Oddly enough, it works fine on my Mac). Here's an excerpt from my wdio file: if(process.env.SERVER == "prod") { ...

I am experiencing issues with my JavaScript not functioning properly in conjunction with my HTML and CSS. I am uncertain about the root cause of the problem (The console is displaying an error message:

I am facing challenges in creating a content slider and encountering issues with its functionality. Specifically, when testing locally, I noticed that the current-slide fades out and back in upon clicking the arrows left or right, but the slide content is ...

Completing a POST request with comma-separated values or an array for autocomplete functionality

After successfully setting up the autosuggest feature, I now want my form to actually post the input values. When I run search.php, I see: {"label":"Henry Gale","value":"[email protected]"},{"label":"Amy Gerges","value":"[email protected]"}, and ...

Updating Time by Adding Minutes using ngFor Loop in Angular 4

I'm currently developing a scheduler that requires user input for start time and the time between two games. I am looking to display the time in a loop using ngFor, incrementing by minutes each time. How can I accomplish this within an Angular 4 HTML ...

Loading a local FBX file in Three.js without the need to upload it

When attempting to load files selected by users in an HTML input, I encountered a problem with the loader expecting a URL in Linux style. I have tried various methods such as using a blob as a URL object, providing raw data to the FBX loader, and even usin ...

Vue: rendering props cannot be utilized with TSX

After switching my setup from JSX in a Vue component to TS with vue-class-component, I found that only the code snippet below works for me (as shown in the example on repo): import Vue from 'vue' import { Component } from 'vue-property-dec ...

Is it advisable to pass useSelector to useState in React?

Hey everyone, I've got a question about preferences for a specific method: When working with a React functional component in TypeScript that retrieves values from Redux State using useSelector, which approach do you prefer? 1) const campaign = us ...

Implementing Javascript to insert IFRAME into the DOM

I'm looking to incorporate an iframe into my webpage. The iframe needs to link to a specific URL. I attempted to add the following code to my HTML, but it's not functioning as expected: document.createElement('<iframe src='http://ex ...

Solving the Issue of Handling Custom Events in Javascript

I've been experimenting with a simple CodePen that features a basic table with three rows. I'm trying to attach event handlers to each row in the table and trigger the event by pressing a button. However, I'm facing an issue where the attac ...

Is there a way to print an HTML page in Landscape mode within my Vue.js project?

I have been able to successfully print an HTML page in Landscape mode using the code below. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,maximum-scale=1.0"> ...

Discover the method for concealing a button using ng-show and ng-hide directives

<div> <div class="pull-right"> <button type="button" data-ng-click="editFigure()" id="EditFigure">Edit Figure </button> <button type="button" data-ng-click="figurePreview()" id="PreviewFigure">Figure Previ ...

Fetching data using Axios from a specified URL

I am currently facing an issue with the npm package axios while attempting to execute a get request to a specific URL. The problem arises as I consistently receive an error code 503. Here is the snippet of code in question: let data, response; response = ...

When implementing multer in an express application, I encountered an issue where req.files appeared empty

Currently, I am facing some issues while attempting to upload various file types to the server using multer in an express application. Whenever I make the request, the server responds with a TypeError: req.files is not iterable. Upon investigation, I notic ...

Show or hide the expand/collapse button based on the height of the container

Looking for a way to hide content in a Div if it's taller than 68px and display an expand option? The challenge lies in detecting the height of the responsive Div, especially since character count varies. I attempted using PHP to count characters bu ...

The reason for duplicating the import of an NPM package in TypeScript (specifically for Firebase Functions)

I recently found this code snippet in the Firebase documentation: import * as functions from 'firebase-functions'; import * as admin from 'firebase-admin'; import 'firebase-functions'; admin.initializeApp(); I'm curious ...

Utilizing Mootools to Access and Obtain the Current Query String Parameters

Is there a way to extract the current querystring values using mootools? I have implemented mootools ajax for php pagination. The initial call includes the following parameters: format=html&nolayout=true&p[0]=1000-1500&p[1]=1500-2000&p[2] ...

What are some effective ways to integrate the WordPress API with ReactJS?

Wordpress recently introduced an API that allows you to make HTTP requests without worrying about routes, as the backend is handled for you. I'm curious, how can I integrate ReactJs with Wordpress API? This has been a frustrating challenge for me be ...

Traverse a dictionary by iterating over its list values

A dictionary is provided like this grouped_data = {"results":[{"id": 101, "name": toto}, {"id": 102, "name": cool}] } This particular dict consists of a list containing dictionaries I hope I haven't made things too complicated for you ;), so no ...

Unable to execute app.get in Express framework of Node.js

const express = require('express'); let router = express.Router(); router.get('/create-new', (req, res, next) => { res.send('<form action="/submit-data" method="POST"><input type="text" name="name"><button ...

Basic demonstration of AngularJS including a module and controller showcased on jsFiddle

I have a question regarding jsFiddle and Angular. I am currently learning the basics of Angular and I noticed that my code only works when I include the controller JS in the HTML pane. You can view my jsFiddle here. Here is the code that works: <div n ...