Removing an element in JSON is resulting in an element that is undefined

Dealing with a JSON Object, I am faced with a challenge where deleting elements results in undefined entries, causing issues in my usage within datatables.

Here is my current approach:

function dTable(presId){
  var allregos = '[{"presId": "a09N0000004UbBnIAK","name": "Something","id": "001N000000Mw7knIAB"},{"presId": "a09N0000004UbBnIAK","name": "test catty","id": "001N000000O98IoIAJ"},{"presId": "a09N0000004UbBnIAK","name": "Something","id": "001N000000Mw7knIAB"}]';
  var newJson;
  var regoValue;
  for (var ke in allregos) {
    if (allregos.hasOwnProperty(ke)) {
      regoValue = allregos[ke].presId;
      if(regoValue != presId){
        delete allregos[ke];
      }else{
        //Instead of delete, considering adding the node to a new JSON
        //But facing challenges in doing so
        //newJson = newJson.allregos[ke];
      }
    }
  } 

  console.log(allregos);
  console.log(newJson);

  j$('#myRegos').dataTable( {
      "data": newJson,
      "destroy": true,
      "columns": [
          { "title":"Name", "mData": "name", "class": "center" },
      ]
  } );
}

Upon logging, the result includes undefined entries:

[undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, Object { presId="a09N0000004W3YLIA0", name="name 1", id="001N000000Mw7knIAB"}, Object { presId="a09N0000004W3YLIA0", name="Call Centre", id="001N000000MvDaMIAV"}, Object { presId="a09N0000004W3YLIA0", name="Who Is", id="001N000000MvIiaIAF"}]

Any solutions to remove these undefined elements?

Another approach I considered was adding appropriate elements to a new JSON instead of deleting. But facing challenges, for example:

newJson = newJson.allregos[ke];

Answer №1

In this scenario, the allRegos variable is an array of objects. A more efficient approach to handle this is by utilizing the standard for loop instead of using for (var ke in allregos), along with if (allregos.hasOwnProperty(ke)). Additionally, I am converting the JSON string into actual JSON data by invoking JSON.parse(allregos). Below is the improved dTable function. It's worth noting that I have added an object with presId='a09N0000004UbBnIAz' to test the outcome when calling the dTable('a09N0000004UbBnIAK');

function dTable(presId){
   allregos = '[{"presId": "a09N0000004UbBnIAK","name": "Something","id": "001N000000Mw7knIAB"}, {"presId": "a09N0000004UbBnIAK","name": "test catty","id": "001N000000O98IoIAJ"}, {"presId": "a09N0000004UbBnIAK","name": "Something","id": "001N000000Mw7knIAB"},{"presId": "a09N0000004UbBnIAz","name": "Something","id": "001N000000Mw7knIAB"}]'; 
   oldJson = allregos; 
   var regoValue;

allregos = JSON.parse(allregos);
oldJson = JSON.parse(oldJson);
newJson = [];



  for( i=0;i<allregos.length;i++){
    regoValue = allregos[i].presId;
    if(regoValue != presId){
        delete allregos[i];
    }else{
        newJson.push(allregos[i]);
    }
  }

  console.log('allregos before:');
  console.log(oldJson);
  console.log('allregos after:')
  console.log(allregos);
  console.log('newJson after:')
  console.log(newJson);

}

Answer №2

To remove unwanted elements, simply overwrite the object entirely.

Imagine you have

var myObject = {
"keyFoo" : "valueFoo",
"keyBar" : "valueBar",
"keyBaz" : undefined
};

To determine which values are not undefined, loop through the object and only keep values that evaluate to true. In this case, you can identify "keyBaz" as it returns false when converted to a boolean, while "keyFoo" and "keyBar" both return true. This process can also be applied to arrays.

You can then update the object like so:

myObject  = {
"keyFoo" : "valueFoo",
"keyBar" : "valueBar"
};

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

Issue with TypeORM Many-to-Many relation returning incorrect data when using the "where" clause

I'm facing an issue with my database tables - User and Race. The relationship between them is set as Many to Many , where a Race can have multiple Users associated with it. My goal is to retrieve all the Races that a particular user is a member of. Ho ...

Display loading images using the Bxslider plugin

Currently, I have implemented a Bxslider on my website with the following HTML markup: <div class="slide"> <a target="_blank" href="#"><img src="image.jpg"/></a> </div> <div class="slide"> <a target="_blank" href= ...

Understanding how to convert XMLHTTPRequest to JSON format in Scala.js is crucial for

I am currently using Scala.js and I am facing an issue with reading a JSON response from my backend. My main struggle is understanding how to handle the response as JSON data. Most of the examples I have come across use JSON.toJson(xhr.responseText), but i ...

Attempting to showcase the text within an <a> element on a <canvas> element while ensuring there are no noticeable visual distinctions

Imagine having this snippet of code on a webpage: elit ac <a href="http://www.ducksanddos/bh.php" id='link'>Hello world!</a> nunc Now, picture wanting to replace the <a> tag with a <canvas> element that displays the same ...

Vue component doesn't update reactively until the template value changes

I have a child component in my Vue application that utilizes Vuex for managing certain values. Currently, when I trigger an action in the parent component, it should also trigger the child component. This is achieved by passing an active boolean prop to t ...

Steps to resolve the issue with an unexpected token in JSON: JSON::ParserError

After utilizing Vagrant for about a month, I encountered an unexpected issue yesterday when running "vagrant up" caused my computer to shut down. View image description here ...

In a REST api, what is the appropriate response for a property that is missing a value?

Is it better for a property with no value assigned to be returned as null, or should the REST API skip such properties entirely? Let's consider a user object example with first_name and last_name. (In the below example, last_name is not necessarily a ...

Transform the blob, which includes an image, into just an image and insert it into the <img> tag

When adding a record to a MySQL database with XAMPP and the "mysql2" package (^3.6.2), I encountered an issue. export const addPage = async (req,res) => { try { if(req.session.user !== undefined) { ...

When I attempt to run JavaScript code on the server, it fails to execute properly

When I run my code on my PC without putting it on the server, it works perfectly fine. However, when I upload it to the server and try to call it, I encounter the following error: Uncaught ReferenceError: crearLienzo is not defined at onload ((index): ...

Dealing with multiple POST requests at once in Node Express JS - Best Practices

I've been working on a Node project with Express to handle incoming GET/POST requests. I have set up routes to manage various types of requests. One specific route, /api/twitter/search, calls a function that uses promises to retrieve Twitter feeds and ...

Accessing specific route parameters in a Vue.js application can be easily achieved by following these steps

I'm dealing with a situation involving nested route settings let routes = [ { name: 'Admin', path: '/prod/:id', component: Admin, meta: { requiresAuth: true, title: 'Admin - Fraud tool' ...

Update and verify a collection of objects in real-time

I have a callback function that retrieves a data object from the DOM. Each time an item is selected, the function returns an object like this: $scope.fClick = function( data ) { $scope.x = data; } When ...

Issue with Jest Test Trigger Event Not Invoking Method

Currently, I am in the process of writing tests for my Vue application. One particular test involves a button that triggers a logout function. The goal is to determine if the function is executed when the button is clicked. Initially, I attempted to mock ...

Trouble with sending semicolons in Node.js MSSQL/MSNodesqlv8 database queries

Trying to create a simple API for interacting with a MSSQL v12 database using Nodejs. Successfully connected to the database with the mssql/msnodesqlv8 package, but encountering issues with parameterized queries. code: 'EREQUEST', number: 102 ...

Issue with Nextjs environmental variables not functioning in JavaScript pages

Currently, I am in the process of developing a Next.js website. Within my JavaScript file, I am fetching data from an API and assigning a token using the .env.local file. However, when attempting to access the .env variable that I've set up, it seems ...

Tips for transforming an array of images (from an input field) into a JSON string

After creating an array of images using var a = Array.from(document.getElementById("id").files); I tried to generate a JSON string of that array using var b = JSON.stringify(a); However, all I get is an empty array. It seems like this issue is common w ...

Why is only the peak of the wave visible? I am eager to showcase the full extent of its beauty

Having an issue with the appearance of a superposed wave using threejs. When displayed, the wave made from plane material only shows the upper half, but when turned upside down using mouse dragging, it appears correctly. // Turn the wave plane upside down ...

What is the best way to delete information from a deeply nested schema in mongoose?

Apologies if this question has been asked multiple times before. I have a mongoose schema for posts with comments stored as an array of sub comment objects. Despite following some advice, I am struggling to successfully remove a sub comment from the postCo ...

Menu changes when hovering

I want to create an effect where hovering over the .hoverarea class will toggle the visibility of .sociallink1, .sociallink2, and so on, with a drover effect. However, my code isn't working as expected. Additionally, an extra margin is automatically ...

What is the method for automatically verifying elements within nested ng-repeats?

My div contains ng-repeat elements that are interconnected. Each ng-repeat element has checkboxes, and I want to automatically check the related elements in other ng-repeats when a top ng-repeat element is checked. Here is the actual representation of the ...