What steps should I take to modify this recursive function so that it can verify the property name of an object?

I stumbled upon the code snippet below online, which effectively and recursively eliminates properties from an object if their values are null, undefined, or 0

const removeEmpty = (obj) => {
    Object.keys(obj).forEach(key =>
        (obj[key] && typeof obj[key] === 'object') && removeEmpty(obj[key]) ||
        (obj[key] === undefined || obj[key] === null || obj[key] === 0) && delete obj[key]
    );
    return obj;
};

I am attempting to tweak it so that it also checks a property name for a value of "index". If it matches, do not delete the property even if its value is 0

For instance, if we process the following object

"page": {
 "index": 0,
 "title": "test",
 "credits": undefined 
}

the desired outcome would be

"page": {
 "index": 0,
 "title": "test"
}

while the current result looks like this

"page": {
 "title": "test", 
}

Answer №1

If you want to ensure certain keys are protected and not deleted during the removal process, you can define them as protected keys:

const protectedKeys = ['key1', 'key2'];

const cleanObject = (obj) => {
    Object.keys(obj)
      .forEach(key =>
          (obj[key] && typeof obj[key] === 'object') && cleanObject(obj[key]) ||
          (obj[key] === undefined || obj[key] === null || obj[key] === 0)
          && protectedKeys.includes(key) === false
          && delete obj[key]
      );
      
      return obj;
};

const sampleData = {
  "sampleObj": {
   "key1": 0,
   "key2": "value",
   "key3": null 
  }
};

console.log(cleanObject(sampleData));

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

When importing data from a jQuery AJAX load, the system inadvertently generates duplicate div tags

Currently, I am utilizing a script that fetches data from another page and imports it into the current page by using the .load() ajax function. Here is the important line of code: $('#content').load(toLoad,'',showNewContent()) The issu ...

Having trouble accessing the text in a paragraph using JavaScript executor and web driver

On a particular website, there is: <p id="tempid" value="Manual Effect">testing the test</p> String value = (String)((JavascriptExecutor) this).executeScript("return window.document.getElementById('tempid').value"); System.out.pr ...

What is the best way to incorporate a text box along with a submit button that triggers a callback to a javascript function when clicked, utilizing either plain javascript or jQuery?

As a beginner in the world of JavaScript, I'm struggling to find the solution to this problem. Any assistance would be greatly welcomed. ...

Modifying the color of a variety of distinct data points

There was a previous inquiry regarding Changing Colour of Specific Data, which can be found here: Changing colour of specific data Building upon that question, I now have a new query. After successfully changing the 2017 dates to pink, I am seeking a way ...

Managing the onChange event for a MaterialUI dropdown component

I'm encountering an issue with validating the MaterialUI TextField component (Country list) wrapped with Autocomplete. I am trying to use the onChange event to enable the Submit button when the country field is filled in. However, the problem arises w ...

Error with the login component in React.js (codesandbox link included)

Hey there! I'm a beginner programmer and I recently dove into a tutorial on creating a Login Form. However, I've run into a few issues along the way. Overview of My Project: The login form I'm working on was built using create-react-app. T ...

"Troubleshooting: How to Fix Issues with document.getElementById on Dynamic Div

Struggling to incorporate div elements and generate graphs with Google charts? The issue arises in the draw function, where attempts to access a div element using document.getElementById() result in null values and an error message stating "container not ...

The autoplay feature for YouTube videos is not functioning on Chrome when viewed on an iPhone

if($('.explore-video-btn').length > 0) { var video_id = youtube_parser($('.explore-video-btn').attr('data-video-url')); } var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api" ...

Mongoose encountered an error when attempting to cast the value "......" as an ObjectId in the "author" path. The error was caused by a BSONError

I'm currently facing an issue with Mongoose in my NextJS project. Specifically, I am encountering a problem when trying to save a document where one of the fields references an ObjectId. The error message I receive is as follows: Cast to ObjectId fail ...

Generating a dynamic form by utilizing a JavaScript JSON object

I need assistance with creating an html form based on a JSON object’s properties. How can I target multiple levels to generate different fields and also drill down deeper to access field details? I am open to suggestions for alternative formats as well. ...

Problem with Ajax causing full-page reload

I currently have a webpage that utilizes JqueryUI-Mobile (specifically listview) in conjunction with PHP and some Ajax code. When the page loads initially, it displays a list generated from a MySQL DB. I want this list to refresh itself periodically witho ...

I've been encountering an issue with the WebClient.DownLoadString function where it inserts """ in front of each element of my JSON data. Is there a way to properly parse the

In my MVC application, I am facing an issue while trying to access a REST Service. I am using the getJSON method to retrieve data from a controller, which internally calls the REST service and returns data in JSON format. However, when executing the Downlo ...

Looking to update the background color of a div every 3 seconds?

Every 3 seconds, I need to change the background color of each div. To do this, I attempted to modify the values in the color array every 3 seconds. For example, the value at index 0 (which is "red") would move to index 1, then the value at index 1 would ...

Testing the NestJS service with a real database comparison

I'm looking to test my Nest service using a real database, rather than just a mock object. While I understand that most unit tests should use mocks, there are times when testing against the actual database is more appropriate. After scouring through ...

JavaScript not functional post AJAX request - navigating AJAX tabs

I am attempting to create a submenu that can update the page content without refreshing by using AJAX tabs to call an external HTML file. While the tabs are functioning properly, I am facing an issue with a JavaScript code within the external HTML file tha ...

Not all words are compatible with word-wrap, don't you think?!

I have a situation where I used the following CSS properties for a div: word-wrap: break-word; text-align: justify; When a single word is too long to fit within the width of the div, it wraps or breaks into multiple lines. However, if a second word with ...

Suggestions for breaking out of the function update()?

Having some trouble escaping my update() function. Here's the attempt I've made: if (score.l1 > 20) { break; } However, all I get is an error message saying "Illegal break statement" ...

How can I easily send JSON using PhpStorm/WebStorm REST client?

Within the PhpStorm / WebStorm version of 2017, there exists a REST client that allows us to send requests and analyze responses. Typically, when I send a POST request using the easy form in the UI to create request parameters, the parameters are formatte ...

When was Chrome first updated to include timezone offset support for Intl.DateTimeFormat()?

My experience with Chromium 121 has been positive using the Intl.DateTimeFormat as shown below: new Intl.DateTimeFormat('en', { dateStyle: 'long', timeStyle: 'long', timeZone: '+0500', }).format ...

Unable to convert a NULL value of type java.lang.String at position 1 to a JSONObject on the Android platform

I have implemented a code that extracts the value from JSON data, checks it, and based on the value, creates a custom layout with three different layouts in a single ListView. Initially, everything was working well. Suddenly, I encountered an error statin ...