Unable to delete a JSON object containing an empty value

Currently, I am dealing with data retrieved from an API that includes both title and author attributes (referred to as title_1 and title_2 in this case). To streamline the process of saving data to my database, I have set a condition where an item is deemed invalid if both title_1 and title_2 are empty.

While this method appears to work correctly for the author attribute, I keep encountering a scenario where an item is still saved even when title_1 is null and title_2 is "". I suspect there might be an issue within how the values are being parsed.

Here is the JSON snippet of the problematic item:

"title_1": null,
"title_2": "",

Upon fetching and parsing the data, the following code is used:

request.get(apiUrl, function(error, response, body) {
      if(!error && response.statusCode == 200) {
        var data = JSON.parse(body);
        callback(error, data.items);
      }
    });

Subsequently, the function removeInvalidItems(data); is called which carries out the filtering process:

function removeInvalidItems(data) {
  for (var i = 0; i < data.length; i++) {
    if ( !isValid(data[i].title) && !isValid(data[i].title_2) ) {
      data.splice(i, 1);
    }
    if ( !isValid(data[i].author) && !isValid(data[i].author_2) ) {
      data.splice(i, 1);
    }
  }
  return data;
};

The validity check is performed using the following logic:

function isValid(attr) {
  if (attr === null || attr === '') {
    return false;
  } else return true;
};

If anyone has insights on why this particular item continues to pass through the isValid() function as valid, please share your thoughts.

Answer №1

It seems that the issue arises when you use splice(i, 1) to remove elements from an array, as this operation shifts the "current index" to the next element in the array. Take a look at the following example where we attempt to remove odd items from an array:

var arr = [1, 2, 3, 4, 5, 6];

for(var i = 0; i < arr.length; i++) {
  if(i % 2 == 1)
    arr.splice(i, 1);
}

alert(arr);

To resolve this issue, adjust the current index by reducing i by 1 after performing a splice operation:

function removeInvalidItems(data) {
  for (var i = 0; i < data.length; i++) {
    if ( !isValid(data[i].title) && !isValid(data[i].title_2) ) {
      data.splice(i--, 1);
    }
    if ( !isValid(data[i].author) && !isValid(data[i].author_2) ) {
      data.splice(i--, 1);
    }
  }
  return data;
};

Additionally, you can simplify your isValid function with the following implementation:

function isValid(attr) {
  return attr instanceof String && attr.length > 0;
};

Answer №2

When consecutive invalid items are encountered in your loop, the second one is not checked because you are altering the array while iterating over it.

To understand this behavior better, try running the following code snippet in a console:

data = [10, 1, 2, 3, 20, 30];
for (var i = 0; i < data.length; i++) {
    console.log('checking i=', i, 'data[i]=', data[i]);
    if (data[i] < 5) {
        console.log('removing i=', i, 'data[i]=', data[i]);
        data.splice(i, 1);
    }
}
console.log('Remaining data:', data);

Instead of directly modifying the array as shown above, a more reliable approach would be to use the filter method.

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

Problem with UV mapping when adjusting texture size

I am currently working on an application to modify minecraft models. To display the drawn texture mapped on the 3D player model, I am using ThreeJS. However, I'm facing a challenge related to changing the texture size. Initially, the texture is mappe ...

When running Javascript code locally, the function works perfectly fine. However, once published, the function encounters a

After spending hours working on cascading dropdown lists and finally getting them to function properly, I published the project only to find that it didn't work as expected. The second list failed to populate. Upon checking Firebug's console, an ...

Are these 2 components very similar, with the only distinction being the unique GET request for each? Should we combine them into one?

There are currently two components in my project that are nearly identical. The HTML structure and CSS rules are the same, with the only difference being the GET request made in the mounted() lifecycle hook. One component fetches all visited places, while ...

Error 415 - Unsupported Media Type in Java Spring framework

Showcasing my Controller: @RestController public class UserController { @RequestMapping(value = "/test", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public User createUser ...

Tips for retaining the value of a variable when the page is reloaded

I need to store the value of the variable loggedIn, as it determines the behavior of a function in appComponent.html. Can you explain how I can achieve this? Template of app component: <li class="nav-item"> <a class ...

Exploring the Power of Observables in Angular 2: Focusing on Targeting an Array Nested Within

I encountered a situation where I was successfully looping through objects in an array within my Angular 2 application using observables. In the client service file, my code looked like this: getByCategory(category: string) { const q = encodeURICompon ...

The controller in Angular uses the $scope symbol _

App.controller('todoController', function ($scope) { // create a message to display in our view $scope.todos = [{ name: 'angular', done: false }]; $scope.clearTodo = function () { $scope.todos = _.filter($scope.tod ...

Identifying the moment when attention shifts away from an element

Is it possible to detect when focus occurs outside an element without relying on global selectors like $(document), $(body), or $(window) for performance reasons? If achieving this without global selectors is not feasible, provide a provable reason expla ...

I keep encountering the following issue: "It seems that the file requested at /images/crown.png is not recognized as a valid image, as it was received as text/html; charset=utf-8."

I encountered an issue while utilizing Next.js. Here is the code snippet where the error occurred: import React from "react"; import { Container, Col, Row } from "react-bootstrap"; import Image from "next/image"; export defaul ...

Updating Variable Values in PHP

Currently, I am working on a project about online shopping using PHP. However, I have encountered an issue regarding changing the currency value. I need to convert the currency to another based on the exchange rate provided. <select onchange=""> ...

Search for a string using the getDate method, then trigger a click event if there is a

Hello everyone, this is my first time posting but I've been silently observing for a while. Exploring selenium with javascript, mocha, and chai I am dealing with a date picker that has multiple buttons, divs, and spans holding the date numbers. I ne ...

Where does the 'Execution Context Destroyed' error originate from in my code?

Currently, I am developing a program to extract forum responses for the online University where I am employed. While I have managed to successfully navigate to the relevant pages, I encountered an issue when trying to include scraping for the list of learn ...

How can we add hover effects to Ionic / Angular components when touching or clicking?

For my app, I need to replicate the hover effect from CSS on mobile devices. Users can click and drag elements, and when they drag over certain elements, I want those elements to change z-index and other styles. Is there a way in Angular / Ionic or even ju ...

Changing the array of objects: various operations on arrays and objects

Array of Data [ {group: 'a', tab: "1", name: 'input1'}, {group: 'b', tab: "1", name: 'input2'}, {group: 'b', tab: "1", name: 'input3'}, {group: 'c', tab: "2", name: 'input4&apo ...

Guide to effectively pass router properties in a Modal/Dialog component within a React application for seamless navigation

I have encountered an issue with my React-Project. I integrated a login component in a modal/dialog form, and the button to access it is located within the Header component of the project. However, I did not set a router path for the login module, which is ...

The size of the .json file exceeds the limit for opening in R using rjson

I'm facing a data challenge with a hefty 5.1 GB json file that I'm struggling to read in R using rjson. My ultimate goal is to create a dataframe from it, but the sheer size seems to be causing obstacles in loading it successfully. Do any of you ...

Build a stopwatch that malfunctions and goes haywire

I am currently using a stopwatch that functions well, but I have encountered an issue with the timer. After 60 seconds, I need the timer to reset to zero seconds and advance to one minute. Similarly, for every 60 seconds that pass, the minutes should chang ...

Create a left-aligned div that spans the entire width of the screen, adjusting its width based on the screen size and positioning it slightly

I have a parent container with two child elements inside. I want the first child to align to the left side and the second child to align to the right side, but not starting from the exact center point. They should be positioned slightly off-center by -100p ...

What steps can be taken to enable JSONIX to handle additional XML elements during the deserialization process?

JSONIX 2.0.12 is truly impressive. I am working with a substantial XML file and I am only looking to convert certain elements into JSON format. Whenever I omit some elements from my mapping file, JSONIX throws an unexpected element error during deseriali ...

How can we integrate fixed-data-table-2 sorting with an existing redux store?

Any help or advice you can offer would be greatly appreciated. I am still fairly new to using react. I recently took on a project for a client that was already in progress, and everything has been going smoothly up until now. I've come across a stumb ...