Search code examples
javascriptjsontypescriptstringify

How to remove nested JSON.stringify() properties


I'm trying to modify a string with Typescript. The string is created by the JSON.stringify() method.

I want to remove the properties "id", "lightStatus" and the "value" attributes of "inputPort" and "outputPort". (I only need their attribute "id".)

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

I tried to do it the following way but it doesn't recognize "inputPort.id" and "outputPort.id". This is what I tried and what it resulted in.

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

The result should include the properties "name", "inputPort id", "outputPort id" and "resistance". Like this:

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

Can anyone help me how I can get rid of the unnecessary properties?


Solution

  • You can pass a "replacer" function that returns the exact value you want.

    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 "" represents the top level object. For that, "name", and "resistance", it simply returns the original value.

    For "inputPort" and "outputPort" it returns the id property.

    Anything else gets undefined, which means it gets omitted from the result.