Tips for eliminating Blank Attributes from a multi-level JavaScript Object

Here is a JavaScript object example:

var test = {"code_operateur":[""],"cp_cult":["",""],"annee":["2011"],"ca_cult":[""]}

After running a function on it:

for (i in test) {  
   if ( test[i] == "" || test[i] === null ) {  
       delete test[i];  
    }  
}

The resulting object is:

{"cp_cult":["",""],"annee":["2011"]}

Although it's close, I actually want to remove the empty "cp_cult" property, which is an array instead of a string like the others.

Important: I am looking for a solution that does not involve manually deleting the key!

Answer №1

It seems like you have two questions to address.

  1. How can I delete a property from an object?
  2. How do I determine if an object is actually an array?

To remove a property from an object, you can use the delete operator.

delete example.object_property;

In JavaScript, arrays are classified as objects, causing the typeof([]) to mistakenly return object. To address this, many developers rely on frameworks like dojo.isArray or custom methods to accurately identify arrays.

Identifying an object as an array doesn't have a foolproof solution. Typically, developers check for array-like methods and properties such as length, push, pop, shift, unshift, among others.

Answer №2

Give this a shot:

function checkEmpty(obj) {
 for(var key in obj){
  if(obj[key]) {
   return false;
  }
 }
 return true;
}

for(index in data) {
 if ( data[index] == "" || data[index] === null || (typeof data[index] == "object" && checkEmpty(data[index])) ) {
  delete data[index];
 }
}

Of course, for more complex objects, you may need more sophisticated algorithms. If the array can contain nested arrays with empty strings that should also be deleted, additional checks will be required.

UPDATE: I've created something that might suit your requirements, feel free to take a look at: http://jsfiddle.net/jVHNe/

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 for the Mongodb find method to handle dynamic queries?

I am new to mongodb and would appreciate some advice on how to efficiently write the following query. In my collection, I have fields for location and date. There are 4 search conditions: Users can search without any parameters. Users can search with da ...

The console log message persists even though the condition statement is present - Vue2

The main goal of my code is to trigger the fetchNumbers() function (which retrieves numbers from an API) when a user scrolls to the bottom of the page, creating an infinite scroll effect. However, I'm encountering an issue with the condition inside th ...

vue form is returning empty objects rather than the actual input data

I am attempting to transfer data from my component to a view in order for the view to save the data in a JSON file. I have verified that the view is functioning correctly as I attempted to log the data in the component and found it to be empty, and the r ...

In ASP.NET, it is possible to only select a single checkbox at a time within a row in a GridView

I have a project where checkboxes are generated dynamically at runtime. I want users to be able to select only one checkbox at a time in each row. Here is my Gridview: <cc1:Grid ID="GrdWorkingCompany" runat="server" OnRowDataBound="GrdWorkingCompany_Ro ...

How can I pass a JavaScript variable to PHP in order to modify the filename of an uploaded file?

How can I modify the filename for the file upload to include an ID prefix? For example: Let's say I have the ID stored in a JavaScript variable called item_id. Is it possible to add data to data.append and use that in the "upload.php" file? I woul ...

Sending data with the request body using Express and Passport

I've created a login application using Express and Passport, but I'm having trouble directing the user to their specific user profile page. The goal is for users to fill out an HTML form and then be redirected to their own profile page (which dif ...

Displaying an image prior to the component rendering in Vue.js

In my Vue application, I have a list of events that are displayed individually. When I visit the page of a selected event, an error message appears in my console: GET http://localhost:1337/undefined 404 (Not Found). However, the image still loads correctly ...

Enhance Laravel 5 by integrating browserify into the Elixir build process

My workflow for transforming coffee to js using browserify, browserify-shim, and coffeeify looks like this: I work with two main files: app.coffee and _app.coffee, designated for frontend and backend respectively. These files are located in resources/coff ...

I have written code in JavaScript, but now I am interested in converting it to jQuery

What is the best way to convert this to jQuery? showDish("balkandish1") function showDish(dishName) { var i; $(".city").css('display', 'none'); $("#" + dishName).css('display', 'block'); } ...

Guide on setting an attribute value with JavaScriptExecutor in Selenium WebDriver

I am attempting to set an attribute value for all instances of the same type of <img> tag on My website, for example: <img src="images/temp/advertisement.png"> and I want to set style="display: none" so that I can hide them. I have tried the ...

Tips for executing an artillery script with customizable parameters

execute my-script.yaml with artillery To access the target, a token is required for authentication. How can I execute the script above using a token? For example: execute my-script.yaml using token 983r2fh29hf2893yr72 ...

What is a reliable method to retrieve the text from the current LI if all LI elements in the list share the

I'm encountering an issue with retrieving the text from LI elements because I have 10 list items and they all have the same class name. When I attempt to fetch the text using the class name or id, I only get the text of the last item. Here is my code ...

JavaScript and jQuery: The Power of Dynamic Arrays

Even though my var email contains a string data, why does my array length always turn out to be 0? (I've confirmed that the data is there by using alert on var email). var emails = new Array(); //retrieve all the emails $('.emailBox ...

Tips for setting limitations on a date picker's minimum and maximum values on an iPhone using JavaScript

I have encountered an issue with my JavaScript function that sets min and max values for the input type date. While it works perfectly on Android devices, I am facing a problem on iPhone where I am unable to restrict the calendar with the specified min and ...

Navigating through the fetch API request when using express js

I'm looking to use the fetch API to send requests and have those requests handled by Express JS. In my setup, I've put together server.js (Express JS), index.html (home page), and signin.html (sign-in page). index.html <!DOCTYPE html> < ...

What is the best way to create a selection input using buttons and save the chosen option in the state?

Check out this snippet showcasing 3 buttons const [role, setRole] = React.useState('') const [active, setActive] = React.useState(false) <Grid container spacing={1}> <Grid item xs={4}> <Button variant='plain&apos ...

Is it possible for window.open to sometimes fail in opening a popup window?

There is a process that requires an update. In order to update a third-party database, I need to call a service provided by them. My Ajax function is working properly. Below is the code snippet for the success callback. $.ajax({ . . success : funt ...

Challenges with synchronizing the scope of global arrays when reading JSON files into objects

I'm attempting to load a JSON file into a global array of objects. The code appears to be functioning correctly, however, I am encountering difficulty extracting the data from the Ajax $.getJSON call and storing it in the global variable. This issue c ...

JavaScript validation controls do not function properly when enabled on the client side

Following the requirements, I have disabled all validation controls on the page during the PageLoad event on the server side. When the submit button is clicked, I want to activate the validations and check if the page is valid for submission. If not, then ...

What causes the statement to be executed before the database transaction?

How can I ensure that the state domains are set only after all DB transactions are completed in my code? Please provide guidance on how to perform this operation correctly. I am using the following method to update the new domains array: setFavorites() { ...