Delete empty value key pairs from JSON data using JavaScript

{
  "top": [{
    "language": "English",
    "value": ""
  }, {
    "language": "German",
    "value": "hASTA"
  }],
  "bottom": [{
    "language": "English",
    "value": "jfgfjg"
  }, {
    "language": "German",
    "value": "fkjhf"
  }],
  "In": "12 am",
  "Out": "3 am",
  "Type": ""
}

Hey everyone, I need help in removing keys with empty values from my data before sending it to the API. Using the filter method caused errors in google sheets. I only want to send data that has non-empty values.

In this scenario,

for the key 'language' with the value empty under German, I should exclude sending top to the API.

The revised JSON to be sent would look like:

{
  "bottom": [{
    "language": "English",
    "value": "jfgfjg"
  }, {
    "language": "German",
    "value": "fkjhf"
  }],
  "In": "12 am",
  "Out": "3 am"
}

Here is the code snippet used:

apidata = userdata.filter(function(x) { return x !== "" }); 

Would appreciate any guidance on how to implement this effectively?

Answer №1

When using userdata.filter, it does not filter the keys of the object.


A more effective approach is to utilize Array.reduce in order to generate a new object based on specified conditions.

const data = {
  "top": [{
    "language": "English",
    "value": ""
  }, {
    "language": "German",
    "value": "hASTA"
  }],
  "bottom": [{
    "language": "English",
    "value": "jfgfjg"
  }, {
    "language": "German",
    "value": "fkjhf"
  }],
  "In": "12 am",
  "Out": "3 am",
  "Type": ""
};

// Recursive function that checks if an object contains a falsy value
function checkFalsy(pointer) {
  if (pointer instanceof Array) {
    return pointer.some(item => checkFalsy(item));
  }
  
  if (typeof pointer === 'string') {
     return pointer.length === 0;
  }
  
  if (Object.keys(pointer).length) {
     return Object.keys(pointer).some(key => checkFalsy(pointer[key]));
  }
  
  return !!pointer;
}

const filteredData = Object.keys(data).reduce((temp, key) => {
  if (checkFalsy(data[key]) === false) {
    temp[key] = data[key];
  }

  return temp;
}, {});

console.log(filteredData);

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

Controller unable to access form inside ng-repeat loop in AngularJS

Looking to access a form object within my controller. The form is located inside an ng-repeat block with a dynamic name, and I should be able to access it since version 1.3. JavaScript: var app = angular.module('app', []); app.controller(' ...

Harvesting the local image file

Currently, I have implemented a form that allows users to upload images and crop them. The process flow has been established as follows: 1. User uploads the image 2. Server processes the image and sends it back to the browser 3. User crops the image a ...

There was an error of TypeError that occurred due to the inability to access the property 'username' of an undefined

var express = require("express"); var app = express(); var morgan = require("morgan"); var mongoose = require("mongoose"); port = 8000; var User = require("./app/models/user"); mongoose.connect("mongodb://localhost:27017/tutorial", function (err) { i ...

When it comes to AFrame+Three.js, which is more efficient: having numerous meshes with minimal triangles per mesh or having a few meshes with a high number of

Currently working with Aframe 1.0.4 and Three.js 111, I am exploring the performance differences between: Whether it is better to have a few entities with a high number of triangles or many entities with fewer triangles each. Specifically, I am debating ...

Ways to extract the value from a jQuery object

How can I retrieve the selected time value using a jQuery plugin and save it on a specific input element within the page? Refer to the plugin and code provided below: http://jsfiddle.net/weareoutman/YkvK9/ var input = $('#input-a'); input.cloc ...

Learn the process of playing a video in an HTML5 video player after it has finished downloading

// HTML video tag <video id="myVideo" width="320" height="176" preload="auto" controls> <source src="/server/o//content/test2.mp4" onerror="alert('video not found')" type="video/mp4"> Your browser does not support HTML5 vid ...

Interested in integrating Mockjax with QUnit for testing?

I recently came across this example in the Mockjax documentation: $.mockjax({ url: "/rest", data: function ( json ) { assert.deepEqual( JSON.parse(json), expected ); // QUnit example. return true; } }); However, I'm a bit confused abou ...

Looking to update the key name in a script that produces a list sorted in ascending order

I have been working on code that iterates through a flat json document and organizes the items into a hierarchical structure based on their level and position. Everything is functioning correctly, but I now need to change the name of the child elements to ...

The conversion from JSONArray to JSONObject is not possible due to an error

I developed an app to extract Json data from a server for use in my application. However, I am encountering an issue where I receive a JSONArray cannot be converted to JSONObject exception when running the project. While I can see all the server data in th ...

Finishing up with regular expressions

I want to create an autocomplete feature for the input field on my website. For instance, when the tab key is pressed, I want the word htt to automatically become tp:// in the input value. This autocomplete should only work if the user inputs "htt" at the ...

Issue with Jquery prevents clicking on hyperlinks

I have a table where table rows can be clicked. However, some cells cannot be clicked if they contain hyperlinks. This is because having both actions - one for clicking the table row and another for clicking the hyperlink - can cause confusion. Therefore, ...

Struggling with implementing the group by feature in AngularJS?

Currently, I am trying to group a select-window by 2 different object arrays - subcategories and rootcategories. Each subcategory has a relation id that links to the rootcategory's id. My goal is to have the dropdown window group the subcategories bas ...

Tips for adjusting the default selection in a second dropdown menu

I have a dilemma with my two dropdown lists, "optionone" and "optiontwo". I am trying to alter the default selected value from "option value=3>3" to option value=3 selected>3 when the user selects 2 from the first dropdown list ("optionone"). <sc ...

Implementing an array of objects within a Vue method

I currently have an object called "Sorteio" which contains a vector of objects named "Resultado", consisting of 6 Resultados. The way I am creating instances of them is as follows: saveSorteio() { var data = { loteria: this.sorteio.loteria, ...

Detecting When an Input has an :invalid Selector in Jquery

Here is the code snippet I am currently working with: HTML <input type="text" data-value="1" data-type="input-records" placeholder="Value" pattern="\d{1,4}$" /> CSS input[type=text]:invalid { background-color: red; } Javascript $("[data-ty ...

Exploring the world of jQuery waypoints and the art of modifying

This is only the second question I'm asking here, so please be gentle! I've been experimenting with jQuery waypoints to dynamically show and hide a border under my navigation menu based on scroll position. For instance, when the sticky nav is ov ...

Tips for accessing nested documents from Firebase in React.js

Here is a snippet of code from my React project: import React, { useState } from "react"; import { db } from "../firebase"; import { collection, Firestore, getDocs } from "firebase/firestore"; function Document() { const ...

Unable to communicate with MediaWiki API using jQuery

My attempt to retrieve content from Wikipedia in JSON format has been unsuccessful: $.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json", function(data) { doSomethingWith ...

Issue with 'firebase.auth is not defined' error following SDK update

I've been using the Firebase JS sdk for web development without any issues for a year now. However, after recently updating my code from version 5.3.1 to the latest 6.5.0 SDK version, I encountered the following error: TypeError: firebase.auth is no ...

What is the best way to access the properties of individual objects within an array of objects in a MongoDB MapReduce JavaScript query?

Need help referencing each property of an object within an array of objects using MongoDB MapReduce JavaScript query? Data example: { "_id": ObjectId("544ae3de7a6025f0470041a7"), "name": "Bundle 4", "product_groups": [ { "name": "camera g ...