What is the best way to eliminate the "1 empty item" from a JSON object using JavaScript?

This is an example json object that has been modified to remove certain values.

{
  name: { first: 'Robert', middle: '', last: 'Smith' },
  age: 25,
  DOB: '-',
  hobbies: [ 'running', 'coding', '-' ],
  education: { highschool: 'N/A', college: 'Yale' }
}

A similar transformation was attempted, but there was difficulty removing the placeholder for an empty item from the array.

{
  name: { first: 'Robert', last: 'Smith' },
  age: 25,
  hobbies: [ 'running', 'coding', <1 empty item> ],
  education: { college: 'Yale' }
}

The challenge now is how to effectively eliminate the placeholder for an empty item from the json object.

Here is an implementation of the code:

axios.get("https://coderbyte.com/api/challenges/json/json-cleaning")
  .then((res) => {
    let parseData = res.data;

    const removeValue = (obj) => {
      Object.keys(obj).forEach(k => 
        
        // console.log(obj[k])
        (obj[k] && obj[k] === "-") && 
        delete obj[k] ||

        (obj[k] && typeof obj[k] === 'object')
        && removeValue(obj[k]) || 
        
        (!obj[k] && obj[k] !== undefined) && 
        delete obj[k] || 
        
        (obj[k] && obj[k] === "N/A") && 
        delete obj[k]


      );
      return obj
    }

    newData = removeValue(parseData)

    console.log(newData)
  })

Answer №1

When it comes to manipulating arrays, using the delete method may not always behave as expected. Deleting an item from an array does not actually modify its length property. For instance, deleting the 3rd element of a 3-element array will result in an array with only two elements, but the length will remain 3.

To handle arrays more effectively, it's better to check if the object is indeed an array and then use the .filter method accordingly.

const payload = {
  name: { first: 'Robert', middle: '', last: 'Smith' },
  age: 25,
  DOB: '-',
  hobbies: [ 'running', 'coding', '-' ],
  education: { highschool: 'N/A', college: 'Yale' }
};
const isGoodValue = val => val && val !== '-' && val !== 'N/A';

const removeBadValues = (obj) => {
  if (Array.isArray(obj)) {
    return obj
      .filter(isGoodValue)
      .map(removeBadValues);
  }
  if (typeof obj === 'object') {
    for (const [key, value] of Object.entries(obj)) {
      if (!isGoodValue(value)) {
        delete obj[key];
      } else {
        obj[key] = removeBadValues(value);
      }
    }
  }
  return obj;
}
const newData = removeBadValues(payload)
console.log(newData)

Answer №2

This method can be utilized

arr.activities.splice(arr.activities.indexOf('-'), 1);

Remember to substitute "arr" with the respective object.

Answer №3

When utilizing the JSON stringify function with a custom replacer argument, any replacements made will also affect nested keys within nested objects:

let data = {
  name: { first: "Alice", middle: "", last: "Johnson" },
  age: 30,
  DOB: "-",
  hobbies: ["swimming", "reading", "-"],
  education: { highschool: "N/A", college: "Harvard" },
};
function customize(key, value) {
  if (value === "N/A" || value === "") {
    return undefined;
  } else if (Array.isArray(value)) {
    return value.filter((item) => item != "-");
  }
  return value;
}
console.log(JSON.stringify(data, customize, 4));

Note: Remember to use JSON.parse() when converting it back into an object.

Answer №4

var data = {
  Name: 'John Doe',
  Age: '-',
  Occupation: 'Developer'
}

function removeEmptyFields(obj) {
  for (var key in obj) {
    if (obj[key] === '-' || obj[key] === undefined) {
      delete obj[key];
    }
  }
  return obj
}

console.log(data);
console.log(removeEmptyFields(data));

Answer №5

Utilize the Array.prototype.splice() method

Implement the following code recursively to remove empty arrays or objects:

const data_row = 
  { name      : { first: 'Robert', middle: '', last: 'Smith'} 
  , age       : 25
  , DOB       : '-'
  , hobbies   : [ 'running', 'coding', '-'] 
  , education : { highschool: 'N/A', college: 'Yale'} 
  } 
     
clearner( data_row )
console.log( data_row )


function clearner( obj )
  {
  const bad = ['-', 'N/A',  '']
  
  for (prop in obj)  
    {
    switch (Array.isArray(obj[prop]) ? 'array' : typeof obj[prop])
      {
      case 'array':
        for (let i=obj[prop].length;i--;)
          if ( bad.includes( obj[prop][i] ))
            obj[prop].splice(i,1); 
        break;
      case 'string':
        if (bad.includes( obj[prop] ))
          delete obj[prop]
        break;
      case 'object':
        clearner( obj[prop] )
        break;
      } 
    if ( obj[prop] && obj[prop].length === 0 )  // empty array or object removal
      delete obj[prop]  
  } }
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

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

Harnessing the power of lazysizes with WebP

I've been working on optimizing our site through the Google Lighthouse audit, and it's clear that images are a major focus. Right now, my main goal is to address the issue of 'Deter offscreen images' highlighted in the audit. To tackle ...

The shade of grey on the curve appears instead of the usual red on the iPad. Any ideas on how to fix

I am having trouble creating a curve like the one shown below on my iPad. The color appears to be gray and does not work properly. Is this a bug with ChartJS or is there a solution to fix this issue? This problem occurs when the type value is set to "lin ...

Encountering an issue with the `className` prop not matching when deploying to Heroku, yet the functionality works perfectly when testing locally

I encountered this specific error message: The className property did not match. On the server: "jss1 jss5" Client side: "makeStyles-root-1 makeStyles-root-5" This issue only arises when deploying to Heroku. Locally, everything runs ...

Implementing the disabled attribute in input text fields with Vue.js

There are 2 URLs that I am working with: /register /register?sponsor=4 The first route, /register, provides a clean input field where users can type freely. The second route, on the other hand, pre-fills the input with a value of 4 and disables it, ...

The text is not appearing properly in an HTML file due to issues with

Hi trying to display the text received from the controller's scope. Here's what I have attempted: HTML: <div ng-repeat="item in sResults"></div> Controller JavaScript: $scope.sResults = []; function App( ){ var Label ...

What steps can be taken to verify that the submitted data is a legitimate numerical pair?

When I receive a string, it should be in the following format: number,number For example: 34.798,52.123 I need to verify that the number is indeed in this format before assigning it to variables and performing calculations. There is also a concern that ...

What is the method to invoke a function within another function in Angular 9?

Illustration ` function1(){ ------- main function execution function2(){ ------child function execution } } ` I must invoke function2 in TypeScript ...

Common causes leading to my header component experiencing hydration errors in Next.js

I am currently developing a job portal and encountering an issue with user authentication using JWT in combination with local storage. The problem arises in my header component when the user is authenticated, and if the web page is reloaded, I receive a hy ...

When using the HTML5 input type time in Chrome and the value is set to 00:00:00, it may not be fully completed

After inputting the html code below <input id="time_in" type="time" step="1" name="duration"> and setting the value in the browser to "00:00:00", everything appears fine. However, upon inspecting the console or submitting the form, the value gets ...

Tips for extracting multiple Json data in Android development

After numerous attempts using the Volley library, I finally managed to parse JSON values. If you'd like to access the JSON values, you can find them here. For the Android code that I used to parse these values, click here. public class GetUSGSjson ...

Issue with data entry: unable to enter the letter 'S' in search field

This bug has been a real challenge for me. It's strange, but I'm unable to type the letter "S" into the search input field. Oddly enough, the keyboard seems to be functioning properly. Please find the sandbox below for reference: https://codes ...

Generating requests using ExpressJS

Is it possible to send a POST request using a GET action? Although everything seems to be working fine, the "TOKEN" does not appear after the post. I am puzzled as to why this is happening. const request = require('request'); exports.g ...

How to Stop AJAX Requests Mid-Flight with JQuery's .ajax?

Similar Question: Stopping Ajax Requests in JavaScript with jQuery Below is the straightforward piece of code that I am currently using: $("#friend_search").keyup(function() { if($(this).val().length > 0) { obtainFriendlist($(this).va ...

How to pass GetServerSideProps into Page component props in Next.js with custom _app.js

Having issues integrating GetServerSideProps into my Next.js app. Despite the network call successfully fetching data and generating the pageName.json, the response data is not being injected into the page props as expected. Below is a snippet of my page ...

Attempting to save an object that references an unsaved transient instance - ensure the transient instance (com.example.model.Salutation) is saved before

I am facing an issue with saving User object containing a reference to the Salutation model class. Even though the Foreign key (salutation_id) in the User table is optional, I am encountering an error when trying to save the User object after merging and f ...

Effortlessly automate clicking with JavaScript or HTML - learn how now!

Does anyone know how to automatically click a button on a page when it loads? I attempted using this JavaScript code, but it didn't work. <a href="javascript:Clickheretoprint()" id="print"> <script type="text/javascript"> $(document).rea ...

What could be causing the npm server error in my Vue.js application?

After recently setting up Node.js and Vue.js, I decided to dive into my first project on Vue titled test. As part of the process, I attempted to configure the server using the command: npm run server However, I encountered the following error message: C ...

Why is React's nested routing failing to render properly?

click here for image portrayal I am currently attempting to integrate react router, specifically a nested router. However, when I click the links on the contact page, no results are being displayed. Any assistance would be greatly appreciated. For more in ...

Receiving JSON objects from Javascript in Django Views

When I attempt to pass a Json Object value from making an API call to my views.py in Django template, I encounter difficulty retrieving the value after an ajax call. let application = JSON.parse(sessionStorage.getItem("appId")); let kycStatus = a ...

What methods can be utilized to accurately determine a user's online status without continuously sending AJAX requests to the server through setInterval?

Seeking effective methods to determine a user's online status I am currently employing an inefficient technique to address this issue: I continuously send AJAX requests to the server at set intervals using setInterval, allowing the server to gauge th ...