"Exploring the depths of JavaScript to completely empty an object

Seeking an uncomplicated method to thoroughly clean basic property values directly on an object, as shown in the example below:

var filled = {
   levelOneObj: {
      property: 'primitive',
      levelTwoObj: {
         property: 'primitive value'
      },
      levelTwoArray: ['primitive', 123]
   }
}

cleanPrimitives(filled);


var filled = {
   levelOneObj: {
      levelTwoObj: {
      },
      levelTwoArray: []
   }
}

I'm hoping to avoid unnecessary complexity and am open to any pre-existing solutions or assistance that may already exist in a library-- thank you for your help!

Answer №1

Here is a possible solution:

function remove_props(obj) {
    for(var key in obj) {
        if(typeof obj[key] == "object"
           && obj[key] !== null
           && !(obj[key] instanceof Array)
           && !(obj[key] instanceof String)
           && !(obj[key] instanceof Number)) {

            remove_props(obj[key]);
            continue;
        }

        switch(typeof obj[key]) {
            case 'string':
            case 'number':
                delete obj[key];
                break;

            default:
                obj[key] = [];
        }
    }
}

Example of how to use this function:

var my_object = {..};

remove_props(my_object);

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

Ways to customize PreBid.js ad server targeting bidder settings

In an effort to implement a unique bidder setting key name within my prebid solution, I have taken the necessary steps as outlined in the documentation by including all 6 required keys. Is it possible to change the key name 'hb_pb' to 'zm_hb ...

Transforming a hierarchical array into a string based on a specific condition

Seeking assistance in properly formatting data using the reduce method const testData = { a: [1], b: [2, 3, 4], c: [] }; Objective is to convert to: a=1&b=2,3,4 Current output: a=1&b=2,3,4& const createUrlString = params => Object.key ...

What is the best way to access the express app within Keystone 6?

I'm currently working with Keystone 6 as my backend system and I'm facing the challenge of integrating Stripe. Stripe requires access to the underlying express app in order to pass a client secret from the server to the client, as explained in th ...

Add a file to your Node.js project with Vue.js integration

I am trying to figure out how I can include another JavaScript file in a similar way to PHP's include function. I'm not interested in the export function, as that only allows you to use variables from other files. Currently, I am using vue init ...

Retrieve information from a JSON API on one server and showcase it on an HTML page hosted on a different server

I have a situation where I need to transfer data from one project (Project1) to another project (Project2). To achieve this, I decided to convert the Project1 data stored in a database into a JSON API and then call it using an HTML page from Project2. Howe ...

Creating a legitimate string using a function for jqGrid editoptions value: What's the best way to do it?

I am encountering an issue while trying to create a string for the editoptions value using a function. The desired string format is as follows: '1:Active;2:Inactive;3:Pending;4:Suspended'. Strangely, when I manually input this string as the value ...

Ways to activate Bootstrap using our javascript

http://getbootstrap.com/javascript/#buttons? They have provided a demo for radio button toggling in Bootstrap. I attempted to implement it in my code, but the active state is not switching. What could be causing this issue? CDNs I am using: Code input ...

Having trouble executing JavaScript upon form submission

Attempting to implement form validation on an email reset page. Here is the code I have written: <!DOCTYPE html> <html> <head> <title> form validation </title> <script> function validateForm ...

Error encountered in React V16.7: The function is not valid and cannot be executed

import React, { useContext } from 'react'; The useContext function is returning undefined. Error Details: Uncaught (in promise) TypeError: Object(...) is not a function Error occurred when processing: const context = useContext(UserCon ...

Is it possible for OrbitControls to maintain rotation based on model origin even while panning?

Let me illustrate my question through an image: Shown here is the top view from the camera, with a grey cube representing a 3D model. The 'X' marks the center of rotation, while the arrow indicates the direction of rotation: Typically, when p ...

How do you modify the up vector of the camera in three.js?

When working with three.js, I encountered a situation where I set the camera's focal point using camera.lookAt(0, 0, 0), but the camera's up vector ended up pointing in a random direction. I have a specific up vector in mind that I want the camer ...

"Passing a variable as an argument to a function in JavaScript

I've been working on setting up a basic loop of animation functions. Each function is stored in an array, and I have successfully logged out each object as a string upon click event. However, I'm encountering difficulties when trying to call the ...

Is the ID Column in the Minimal Material Table Demo not appearing as expected?

Hey there, I'm in the process of developing a simple demonstration of a material table - Take note that this is a stackblitz link and for some reason, the id column isn't showing up. Here's a snippet from my app.component.ts: import { C ...

Exploring the Power of Oembed with Hulu (and delving into the World of JSON

If anyone has insight into this process, it would be greatly appreciated. Here's the situation: I am trying to retrieve the embed URL from a Hulu video URL (e.g. 'www.hulu.com/watch/154344') using Javascript (jQuery is fine). Just to clarif ...

The home navigation item's color remains active, even after changing the NavLink in ReactJs

When using NavLink for Routing and showing the active item of selected items, I am facing an issue where the home item is always shown as active even when switching to other items. This problem does not occur with items other than home. Can someone help m ...

Leverage the URL parameter with variables in HTML using AngularJS

I'm facing the same issue as yesterday: trying to extract and utilize parameters from the URL within my HTML page using AngularJS. What am I doing wrong? The parameter I need to work with is: https://url.com/index.html?user I aim to retrieve the "u ...

The button's background color remains the same even after clicking on it

In my exploration of Vue.js, I decided to create a simple project to grasp the concept of class binding. I wanted to add functionality to each button component, so that when a button is clicked, it would change its color or background color to something ot ...

Validation in Angular2 is activated once a user completes typing

My goal is to validate an email address with the server to check if it is already registered, but I only want this validation to occur on blur and not on every value change. I have the ability to add multiple controls to my form, and here is how I have st ...

Navigating pages with AJAX and restoring browser state

Exploring the world of AJAX-based navigation on a Rails website, with some basic jQuery hooks written in Coffeescript: $(document).on 'click', 'a.ajax_nav', (e) -> window.history.pushState(null, "page title", this.href) $(window) ...

Issue with Material UI: Style overrides for nested components are not being applied

Having recently delved into CSS in JS techniques, I've hit a roadblock when it comes to styling components in Material UI, particularly with overriding styles of nested elements. Although I have been referring to the official documentation, I still fi ...