Eliminate any elements that are not set in a JSON document

My task is to remove empty elements from a JSON document that has an unknown depth, similar to the one below:

{
    "a": {
        "a1": ""
    },
    "b": {
        "b1": "",
        "b2": {
            "b21": "",
            "b22": {
                "b22z": "",
                "b22x": ""
            },
            "b23": ""
        },
        "b3": ""
    },
    "c": "only non-empty field"
}

I decided to use JSON.parse to extract the object and then manipulate it. However, after attempting the function found in this post, I encountered issues:

function filter(obj) {
    $.each(obj, function(key, value){
        if (value === "" || value === null){
            delete obj[key];
        } else if (Object.prototype.toString.call(value) === '[object Object]') {
            filter(value);
        } else if ($.isArray(value)) {
            $.each(value, function (k,v) { filter(v); });
        }
    });
}

Running this function on my object resulted in empty properties remaining, which was not the desired outcome:

https://i.sstatic.net/RWHA2.png

I have tried several modifications but haven't been successful. Any suggestions would be greatly appreciated. Thank you.

Answer №1

Here is the code snippet again for better visibility:

function removeEmptyEntries(object) {
    let allEmpty = true;

    for (let item in object) {

        if (typeof object[item] == "object") {
            if(removeEmptyEntries(object[item]))
            {
                delete object[item];
            } else {
                allEmpty = false;
            }

        } else if (object[item]=="") {
            delete object[item]
        } else {
            allEmpty = false;
        }
    }

    return allEmpty;
}

Please note that this code was written off the top of my head and has not been tested.

Answer №2

Do you require this specific type of solution?

function eliminate(object) {
    for (let item in object) {
        if (typeof object[item] == "object") {
            eliminate(object[item])
        } else {
            if ((object[item]=="")) {
                delete object[item]
            }
        }
    }
    return object
}

const obj = {
    "a": {
        "a1": ""
    },
    "b": {
        "b1": "",
        "b2": {
            "b21": "",
            "b22": {
                "b22z": "",
                "b22x": ""
            },
            "b23": ""
        },
        "b3": ""
    },
    "c": "only non-empty field"
}

console.log(eliminate(obj))

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

My function won't get called when utilizing Angular

My Angular code is attempting to hide columns of a table using the function shouldHideColumn(). Despite my efforts, I am unable to bind my tags to the <th> and <td> elements. An error keeps popping up saying Can't bind to 'printerColu ...

Increase the current time by 50 minutes

I have a dropdown menu with various time options like this: <select name="" id="delyvery-hour"> <option value="18:00">18:00</option> <option value="18:05">18:05</option> <option ...

The React initialization and construction process leads to excessive memory consumption

Hi there, I am facing an issue while trying to start or build my React app as it keeps giving me a heap out of memory error. Despite adding the --max_old_space_size=8192 flag to my script, the problem persists. yarn run v1.22.5 $ react-scripts --max_old_ ...

Validation error occurs in the jQuery form

I've been working on creating a basic form with validation, but for some reason the validation isn't working as expected. I've checked all my tags to make sure they match up, but something seems off with the closing tags at the end of the fo ...

Develop a data structure that resembles a map

I am currently working with a product model that looks like this: export class Product { id: number; name: string; price: number; url: string; description: string; constructor() { this.id = 1; this.name = '&apo ...

The pagination feature is malfunctioning and is displaying all elements on every page instead of correctly displaying a

I am currently working with BootstrapVue 3 to create a component that uses a b-table. The issue I am facing is with the pagination functionality using b-pagination. My intention was to display only 2 objects per page, but instead of that, all objects are ...

Utilizing json4s in Scala Play Framework to handle JSON data with JsNull value

Just starting out with Scala and facing a challenge in handling the JsNull value. I'm currently using json4s to convert JSON to a map, but wondering if I should be converting JsNull to an Option. For instance: Using Play JSON to create JSON val js ...

The PopupControlExtender in ajaxToolkit seems to be malfunctioning when used with a textbox that has Tinymce

I recently built a website using ASP.NET, and I have a feature where a small tooltip appears on the right side of a text box when the user focuses on it. To achieve this, I am using the ajaxToolkit:PopupControlExtender in my code. <asp:TextBox ...

The data passed into the child component via Input() retains its original value even after being modified within the child

While passing an object containing data length and an array of objects to a child component, I noticed a strange behavior. Even after changing the data in the child component and reloading the page, the edited property still persists. To visualize this is ...

Combining server-side and client-side routing in AngularJS: A comprehensive guide

Currently, I am in the process of transitioning a project to an Angular-based Single Page Application (SPA). The project is originally built using node/locomotivejs and serves templates from the server side. Due to its large size, we are converting it to A ...

React Native reminder: Unable to update React state on a component that is unmounted

I am seeking clarity on how to resolve the issue in useEffect that is mentioned. Below is the data for "dataSource": [{"isSelect":false, "selectedClass":null, "zoneId":1026, "zoneName":"tomato"}, ...

Establishing the state prior to a return statement is inevitably unsuccessful as the react component is not yet fully

I've come across similar questions like mine, but I've had trouble finding a solution that works for me. I'm feeling stuck on how to tackle my current issue. In my project, I am generating a fairly large grid (2D array) where I map it out a ...

Is it possible to use a Wcf polling duplex service with a client that is not using Silverlight?

I've been developing an online TicTacToe game and I'm utilizing a WCF polling duplex service to make it work. However, after dedicating a whole week to research, it seems that this service is only possible for Silverlight clients. If anyone is a ...

Dual models integrated into a single timepiece

Let's say I have a watch function that monitors a model in this way... $scope.$watch('number', function () { $scope.number = $scope.number.replace(/\D/, ''); $scope.number = $scope.number.replace(/\s+/g, '&a ...

Error: Node.js encountered an unexpected identifier in the syntax

I'm encountering an issue with my web application. The error keeps popping up. app.get("/campground/:id/comments/new",function(req,res){ camp.findById(req.params.id)({ if(err) console.log(err); else ...

Complete a form when a link or button on the webpage is clicked

I have a variety of links and buttons on my webpage, and they are generated dynamically. I am unable to assign an onclick event to each one individually. My goal is to submit form data to the next page whenever any link or button on the page is clicked. ...

Error: Trying to assign a value to null in the innerHTML property has resulted in an uncaught TypeError

I've been struggling with an issue in my code where the innerHTML is not updating the content inside the content_holder div. Any help would be greatly appreciated! Despite trying different methods and conducting extensive research, I haven't bee ...

Update the URL and parse the data in a Backbone collection

For the purpose of development, I am looking to replace the collection with fake JSON results either from a JSON variable or a JSON file. However, I encountered an error when attempting to do so using url http://jsfiddle.net/qhoc/uZhM8/ GET http://fiddle ...

JavaScript data manipulation: Determining percentage change within a nested JSON structure

Provided is a JSON file structured like this... data =[ { key: "london", values: [ {day: "2020-01-01", city: "london", value: 10}, {day: "2020-01-02", city: "london", value: 20}, {day: " ...

The comments entered into the box are being overridden instead of being posted

I have encountered an issue where, upon hitting the post button, the comment is successfully posted on the page. However, if I hit the button again, it seems to override the previous comment. Can someone please provide clarification on this matter? Additio ...