In JavaScript, it is impossible to remove an object key without using quotation marks

I encountered an issue when attempting to remove keys from a JSON object:

var data = this.data;
  Object.keys(data).forEach(function(key) {
      if (isEmptyProperty(data[key])){
        delete data[key];
      };
  }); 

The loop above iterates through a JSON object with the following structure:

{ notes: [],
 isHostessGift: false,
  playbook: {},
  location: {},
  wine: { ingredient: false, pairing: false },
  coupons: [],
  ingredients: [{ item: 'e' }],
  categories: { dishType: ["Beverage"], mainIngredient: ["e"] },
  directions: [{ step: 'e' }],
  headline: 'jnj' }

It aims to eliminate keys with empty arrays like 'coupons' and 'notes'

However, it's not working as intended. Interestingly, when I manually added quotes around the keys in the data:

{ "notes": [],
isHostessGift: false,
  playbook: {},
  location: {},
  wine: { ingredient: false, pairing: false },
  "coupons": [],
  ingredients: [{ item: 'e' }],
  categories: { dishType: ["Beverage"], mainIngredient: ["e"] },
  directions: [{ step: 'e' }],
  headline: 'jnj' }

The keys were successfully removed. What could be causing this difference in behavior?

function isEmptyProperty(obj) {

for (var key in obj) {
    if (hasOwnProperty.call(obj, key)){
       if(typeof obj === 'function') return false;
       if (obj == null)       return true;
       if (obj.length === 0)  return true;
       if(_.isEmpty(obj))     return true; 
       if (obj.length > 0)    return false;
    };
    return false;
}


 }

Answer №1

Previously mentioned was the issue with isPropertyEmpty, where it would return undefined for empty arrays. I have since revised it and it seems to be functioning correctly.

var doc = { 
    "notes": [],
isHostessGift: false,
    playbook: {},
    location: {},
    wine: { ingredient: false, pairing: false },
    "coupons": [],
    ingredients: [{ item: 'e' }],
    categories: { dishType: ["Beverage"], mainIngredient: ["e"] },
    directions: [{ step: 'e' }],
    headline: 'jnj'
};

Object.keys(doc).forEach(function(key) {
    if (isPropertyEmpty(doc[key])) {
        delete doc[key];
    };
});


function isPropertyEmpty(obj) {
    var hasOwnProperty = Object.prototype.hasOwnProperty;

    if (obj === null || obj.length === 0) {
        return true;
    }
    
    if (typeof obj === 'function' || typeof obj === 'boolean') {
        return false;
    }

    if (obj.length > 0) {
        return false;
    }
    
    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) {
            return false;
        }
    }

    return true;
}


console.log(doc);

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

What is the best way to convert JSON into an Angular 7 object?

My challenge involves consuming a web API that provides the following data: { "FileStatuses": { "FileStatus": [ { "accessTime": 0, "blockSize": 0, "childrenNum": 13, "fileId": 16396, ...

Is it possible to make the entire div clickable for WordPress posts, instead of just the title?

I am currently facing an issue where only the h1 element is linked to the post, but I want the entire post-info div to be clickable. Despite my efforts, I haven't been able to make the whole div clickable, only the h1 element remains so. Below is the ...

Choose and duplicate all components contained within Code tag utilizing Jquery

I am in search of a jquery method to copy an entire code block. I currently have a script that copies text using the select() method, which is limited to input fields and textareas according to the jquery documentation. Therefore, I am looking for a solut ...

I have successfully implemented ngCordova local notifications, but now I am looking for a way to make it trigger for each individual

Is there a way to trigger a notification on every logged-in user's mobile device when a value is changed and saved in Firebase? Currently, I am able to send a local notification using ngCordova when a user enters text in an ionicPopup with textarea. H ...

How to extract values from a JSON array without a root key?

I have been attempting to deserialize an array using Newtonsoft in order to display a list of values. Unfortunately, no matter what I try, I keep encountering the following error: Exception thrown: 'System.NullReferenceException' This is the JSO ...

Learn the art of closing an AngularJS accordion automatically when another accordion is opened within an AngularJS application

I have encountered an issue with the AngularJS accordion functionality. It seems that when I have multiple accordions, such as accordion-1, accordion-2, and accordion-3, they all open simultaneously if clicked on individually. My main concern is: How can ...

Swapping React Components with a Click of a Button

My webpage features a button labeled "Sign Up". Once this button is clicked, I want it to display a new component named "SignUp" in place of the original button. Currently, my method involves using setState to trigger the rendering of the new component upo ...

Accessing Row Data from a Material Table using a Button Click, Not through Row Selection

My React component features a material table view, shown here: https://i.stack.imgur.com/OUVOD.png Whenever the delete icon is clicked in the table, I want to access the rowdata associated with that particular row. However, all I am able to retrieve is ...

"Unleashing the power of custom servers to tap into the rendered HTML of Next

In my quest to serve a server-side generated page as a file using next.js, I decided to extract the rendered content within a custom server.js file: const express = require('express'); const next = require('next'); const port = parseIn ...

How to retrieve a variable from an object within an array using AngularJS code

I recently started learning TypeScript and AngularJS, and I've created a new class like the following: [*.ts] export class Test{ test: string; constructor(foo: string){ this.test = foo; } } Now, I want to create multiple in ...

transferring information to a PHP page using JavaScript without using AJAX requests or form submissions

I am currently working on a PHP page where I receive POST data using some functions, without relying on AJAX for page refresh. At the moment, I have a form that includes hidden fields holding dynamic data, which is then sent using JS like this: document.m ...

Experiment with re-rendering advertisements using Vue.js

Hey there, I'm new around here so please be patient with me if I make any mistakes :D So, onto my question! I have a website built with vuejs and I want to incorporate some ads into it. To do this, I have created some components: <template> ...

Implementing a JSON array to object conversion in an Express REST API

After conducting a test on a REST API using Postman, the outcome was as follows: { "success": true, "message": "success", "data": [ { "id_buku": 9, "judul_bu ...

jQuery efficiently handles large amounts of text data transfer (gradual loading)

The issue at hand: My website relies on jQuery AJAX (post) for navigation, meaning the page doesn't refresh every time a user moves to a different section. This setup requires me to fetch data using AJAX and present it dynamically. While this works w ...

Navigating through _middleware on Next.js to inspect cookies

I am facing an issue with using _middleware in Next.js. I am trying to retrieve the JWT token and verify it within that _middleware. Here is my code snippet: import {NextResponse} from "next/server"; import {verify} from "jsonwebtoken"; ...

NG6002 error: This error is showing up in the imports of AppModule, even though it has its own set of issues

Running Angular 12 locally is smooth with no errors in the project build. Local Configuration: Angular CLI: 12.0.5 Node: 12.16.3 Package Manager: npm 6.14.4 OS: win32 x64 Angular: 12.0.5 However, when attempting to build the project on a Linux se ...

Utilizing PHP and Ajax for paginating JSON responses

I have successfully parsed some JSON data from the YouTube API, but I am running into a limitation where only 50 results can be shown per request. I am looking for help on how to implement pagination using either JavaScript or Ajax in my PHP script. The go ...

Validating decimals in a text field with either JavaScript or jQuery

I need to implement text field validation on the keyup event. The text field should only accept money type decimals such as: (12.23) (.23) (0.26) (5.09) (6.00) If any incorrect value is entered, it should revert back to the previous value and remove the ...

Writing and altering content within the <code> element in Chrome is unreliable

Utilizing a WYSIWYG Editor with contenteditable functionality allows users to input "code snippets" using a <code> element. Here is an example: <div contenteditable="true"> <p> This is a paragraph with an <code>inline s ...

Tips for defining a distinct series of key-value pairs in typescript

Having experience with a different language where this was simple, I am finding it challenging to articulate a sequence of pairs: Each pair is made up of two basic elements (such as strings or numbers) Each element may appear multiple times within the lis ...