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

Is it possible to remove content from a Content Editable container?

JSFiddle <div contenteditable="true"> <p>Trying out editing capabilities of this paragraph.</p> <figure> <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/ima ...

Oops! There was an issue trying to solve the command "/bin/bash -ol pipefail -c npm run build" while deploying a Next.js app on Railway. Unfortunately, it did not complete successfully and returned an exit code of

[stage-0 8/10] RUN --mount=type=cache,id=s/8a557944-4c41-4e06-8de9-06bfcc5e8aaf-next/cache,target=/app/.next/cache --mount=type=cache,id=s/8a557944-4c41-4e06-8de9-06bfcc5e8aaf-node_modules/cache,target=/app/node_modules/.cache npm run build: 17.62 17.62 ...

How can I create a custom checkbox in React Bootstrap without specifying an ID

I'm struggling to understand why this seemingly straightforward Bootstrap custom checkbox isn't functioning as expected. My project involves React, Bootstrap, and React-Bootstrap. import React from "react"; import ReactDOM from "react-dom"; impo ...

Is there a way to efficiently update specific child components when receiving data from websockets, without having to update each child individually?

Currently, my frontend requires updated data every 2 seconds. The process involves the frontend sending an init message to the backend over a websocket. Upon receiving this message, the backend initiates an interval to send the required data every 2 second ...

The incessant loop of JSON Lint outputs continues indefinitely

My training data is stored in a JSON file and it seems like I accidentally added a character where it doesn't belong. This mistake has resulted in an error message when trying to load my JSON file: Can't parse json file "data/converted_data.jso ...

Guide for transferring information from JavaScript to PHP on the same page

My dilemma lies in transferring data from my JavaScript script to PHP code for use within a query. Despite numerous attempts, I have been unsuccessful in achieving this. Below is my script for uploading files using an input type: file, where the URL is sto ...

The function for the "load next page" action in ngInfiniteScroll is continuously triggered

After attempting to implement infinite scrolling using the "loading remote data" example from the ngInfiniteScroll website, I am facing a problem. The function nextPage() is being called continuously until all records have been loaded (controlled by an of ...

Bing Translator and XMLHttpRequest are two powerful tools for translating and

When running the code snippet below, I encounter an issue where I am not receiving status 200 and responseText. However, when using the following URL: http://api.microsofttranslator.com/V2/Http.svc/GetLanguagesForTranslate?appId=F1B50AB0743B541AA8C070890 ...

Failed to set Firebase data: The first argument provided contains an undefined property

When it comes to creating an event, here's my approach: export const handleEventCreation = ({ title, time, location }) => { const newEventKey = firebase.database().ref('/events').push().key; const updates = {}; const eventDetails ...

How can I transfer a variable from one webpage to another within the MEAN stack?

This is the Angular View Code: <button class="btn btn-primary" ng-click="edit(obj._id)">Edit</button> Here is the Angular Controller code: $scope.edit=function(id) { console.log('edit() called........'); console.log(id); ...

Modify KeyboardDatePicker to display the full name of the day and month

Date Selector Hey there, I'm looking to modify the date format from Wed, Apr 7 to Wednesday, April 7. Is there a way to display the full name of the day and month instead of the short abbreviation? ...

When attempting to execute a script that includes document.write, it will not function as expected

Our web program is utilizing ajax and jquery, specifically Netsuite. I've been attempting to adjust elements on a page using document.ready and window.load methods in order to load an external script onto the page. Regardless of whether I load this ex ...

Creating a properly formatted JSON in PHP: A step-by-step guide

When I try to generate a JSON with data from my database, everything works fine until I put the data in JSON format. It seems like something is not right: {"comment":[{"id_comment":1,"photo":"imgU\/default.png","full_name":"MercadoPago","comment":"Pr ...

unable to modify the content within a div by clicking on a link

Lately, I've been experimenting with a code snippet I found on this fiddle: http://jsfiddle.net/unbornink/LUKGt/. The goal is to change the content of a div when clicking on links to see if it will work on my website. However, no matter which link I c ...

Having trouble with installing npm package from gitlab registry

I recently uploaded my npm package to the GitLab package registry. While the upload seemed successful, I am facing an issue trying to install the package in another project. When I run npm install, I encounter the following error: PS E:\faq\medu ...

Initiating, halting, and rejuvenating a timer in JavaScript

Here is a simple code snippet where I'm experimenting with starting, stopping, and resetting a JavaScript timer. The goal is to have a timer running on a page that sends a message once it reaches the end of its countdown before restarting. The stop b ...

Unable to interpret Python/Django-generated JSON object on client side

I'm encountering an issue while passing a data object from a Python/Django application to the frontend using AJAX in JSON format. Despite everything appearing to be functioning correctly, I am unable to properly parse the JSON object within JavaScript ...

Adjust the color of the text as it scrolls by

As I work on developing my website using the Neve Theme on WordPress, I have encountered an issue with customizing the header block. I am using a plugin to set a background color for the header after scrolling 100px down the page, but this makes the text h ...

Having trouble with JQuery's append method on the <head> tag?

I am having an issue with this particular code block. It seems to be unable to insert the meta tag into the head section. Any suggestions on how to resolve this problem? <html> <head> <title>hello world</title> </head> < ...

Using the `ng-if` directive in Angular to check for the

I need to output data in JSON format using items. To display a single item, I utilize ng-repeat="item in items". Additionally, I can access the user object of the currently logged-in user with user. Every item has the ability to belong to multiple wishlis ...