The Splice function is malfunctioning due to issues with the object (the indexOf function is not recognized)

I am currently dealing with an object that looks like this:

Object {val1: "Hello", val2: "", dt1: "pilo1", dt2: "pilo2", lo1: "log1"}

My goal is to remove any keys within the object that have empty values ("").

I attempted the following code snippet:

 angular.forEach($scope.test,function(value,key){
          if(value==""){
                    var index = $scope.test.indexOf(key);
                    $scope.test.splice(index,1);
          }
  });
//$scope.test={val1: "Hello",val2: "",dt1:".......}

However, there is one more important consideration - the keys in the object are not fixed. They may change based on certain conditions. For example:

{val1: "",val2:"Hello1",val3:"",val4:"Hello3",dt1:""}
Therefore, I am seeking a generic solution.

Answer №1

Removing an object property using the splice method is not recommended. Instead, you should utilize the delete operator.

angular.forEach($scope.test,function(value,key){
    if(value==""){
        delete $scope.test[key]
    }
});

If you want to learn more about the delete operator, check out this resource here. Below is a snippet demonstrating the usage of the delete operator in plain JavaScript.

var obj = {val1: "Hello", val2: "", dt1: "pilo1", dt2: "pilo2", lo1: "log1"};
console.log('Before we call delete');
console.log(obj);
Object.keys(obj)
      .forEach(function(key){
          if(obj[key]===""){
              delete obj[key];
          }
});
console.log('After we call delete');
console.log(obj);

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

Processing .dat files using JavaScript

Currently, I am attempting to utilize JavaScript to upload a file named example.dat. Initially, I believed that the correct approach would be using fileReader; however, it appears that this method is unable to process this specific format. The objective i ...

Integrating React js with Layout.cshtml: Mastering the Fusion of React Routing and ASP.NET MVC Routing

My current project involves an ASP.NET MVC core application with the View written in cshtml. The routing follows the conventional asp.net mvc routing pattern. However, I've recently implemented a new module using React JS. Now, I'm faced with the ...

Trouble arises when attempting to create a two-column layout using Material UI's <Grid> component

My goal is to create a two-column layout where each column takes up half of the screen and has equal height. To better illustrate, take a look at this image. The code I've tried so far is not working as expected: import React from "react"; import { ...

Ways to retrieve text like innerText that functions across all web browsers

I need to retrieve the text from a Twitter Follow button, like on https://twitter.com/Google/followers Using document.getElementsByClassName("user-actions-follow-button js-follow-btn follow-button")[0].innerText correctly displays the text as: Follow ...

add a JavaScript variable to a JSON data structure

My JSON object is valid and it's called list_to_book_for: {"fold1-key1":{"name":"Van Antwerpen"},"fold2-key2":{"name":"Delporte"},"fold3-key3":{"name":"Lallemand"}} In order to add the content of a variable into this object, I have the following str ...

Accessing data from localhost using Vue.js and Axios is restricted due to CORS policy and the error "Access to XMLHttpRequest" may be

Having a minor issue... Trying to retrieve a basic json file from my server for testing purposes (not an actual API). Utilizing VueJS and axios. Here is my code : getServicesAPI() { axios.get("http://51.91..../dist/API/Services.json").the ...

Whenever I attempt to generate a forecast utilizing a tensorflow.js model, I encounter the following error message: "Uncaught TypeError: Cannot read property 'length' of undefined."

I'm currently working on a project to build a website that utilizes a deep learning model for real-time sentiment analysis. However, I've encountered an issue when using the model.predict() function. It throws an error message: Uncaught TypeErro ...

The presence of "href="#"" is causing a disruption in the Angular

Recently, I set up a route in my Angular project like this: var app = angular.module("MSL", []) .config(function($routeProvider, $locationProvider){ $routeProvider .when("/dev.html", { redirectTo: "/template1" }) . ...

Enhancing Transparency of WMS Layers in OpenLayers

I need help figuring out how to add transparency to a WMS layer in openlayers. Here is the current javascript code for a non-transparent layer: var lyr_GDPSETAAirtemperatureC = new ol.layer.Tile({ source: new ol.source.TileWMS(({ ...

Struggling with React Js and need some assistance?

I'm completely new to React Js and encountering issues with my code. Here's what I have: Here is the content of my script file named Main.jsx. This file gets compiled by React, and the output is stored in main.js under the 'dist' folde ...

Switching out text when hovering with Jquery or JavaScript

Is there a way to use jQuery or JS to make the text and icon disappear when hovering over a div, and replace it with "Read More"? I've looked at some guides but they only remove one line of text instead of clearing the entire div and displaying "Read ...

Angularjs displays an error message stating, "Unable to assign value to property that is undefined"

Whenever I try to set a property, I encounter an error message stating "cannot set property of undefined". vm.dtr1 = {}; // Could it be that I have incorrectly initialized this? vm.dtr1.date1 = {}; // Could it be that I have incorrectly initialized this ...

Learn how to customize button styles in ExtJS with the pressedCls configuration option

Is there a way to change the color when a button is pressed? I tried using the pressedCls config but it didn't work. How can I fix this issue or is there another method to set the CSS when a button is pressed? Thank you so much! Javascript: Ext.crea ...

Does the ThreeJS Bloom Example provide the desired outcome when copied line by line?

Comparing the results of my bloom filter with an online example reveals some discrepancies. Online Example: https://i.sstatic.net/l7hOtm.png My Output: https://i.sstatic.net/vc7ytm.png Although I have copied the example code exactly, my output does no ...

"Are you greeted with a new tab pop-up on your initial visit

I am trying to display a helpful message in a new tab the first time someone visits my website, but I am encountering issues. Below is the code snippet I am using: <html> <?php $cookie_name = "visited"; $cookie_value = "1"; ...

Can functions be used as keys in a collection in JavaScript's map?

Using functions as keys in JavaScript can be tricky because for js objects, functions are converted to their "toString" form. This poses a problem if two functions have the same body. var a = function() {}; var b = function() {}; var obj={}; obj[a] = 1; o ...

An effective way to utilize the h() function in Vuejs to render a component instance

I'm currently working on a Vuejs component setup that resembles the following structure: <template> <button @click="generateItem()">Add item</button> <div class="container"></div> </template> ...

IE encounters issues making Ajax calls when transitioning from secure HTTPS requests to insecure HTTP requests

I am currently facing an issue with my ajax CORS request. It is functioning perfectly on all browsers except for Internet Explorer. In IE, the request doesn't even attempt to go through and fails instantly without any error messages appearing in the c ...

Intercepting HTTP requests on specific routes with Angular 4+ using an HTTP Interceptor

I've developed an HTTP_INTERCEPTOR that needs to function on certain routes while excluding others. Initially, it was included in the main app module file. However, after removing it from there and adding it to specific modules, the interceptor conti ...

An elaborate warning mechanism in Redux-observable that does not trigger an action at the conclusion of an epic

I'm currently working on implementing a sophisticated alert system using redux and redux-observable. The requirements are: An action should request an alert: REQUEST_ALERT An action should create an alert and add an ID: SET_ALERT (handled in the ep ...