Tips for clearing object values without deleting the keys: Resetting the values of an object and its

Upon creating a service to share data among multiple components, it became necessary to reset the object values once the process was complete. To achieve this, I attempted the following: this.UserDetails = {}; This successfully cleared the values and removed any nested objects, effectively resetting the service object to its default state.

Many thanks.

Below is my service file:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class dataService {
  constructor() { }
  UserDetails: any = {
    key1 : '' ,
    key2: {
      Status: false,
      Label: ''
    },
    key3: {
      Status: false,
      Label: ''
    },
    key4: {
      Status: false,
      Label: ''
    },
    key5: '',
    key6: '',
    key7: new Date(),

  }
}

After assigning values in components, the UserDetails object appears as follows:

UserDetails = {
    key1 : 'value 1' ,
    key2: {
      Status: true,
      Label: 'label 1'
    },
    key3: {
      Status: false,
      Label: 'label 2'
    },
    key4: {
      Status: true,
      Label: 'label 3'
    },
    key5: 'key value 1',
    key6: 'key value 2',
    key7: new Date(),

  }
}

Once the data is passed to the backend, it is necessary to reset to the default values in the service file.

Answer №1

Consider creating a class called UserDetails and filling it with data. When resetting, simply return a new instance of this class.

Take a look at the code snippet below for a demonstration. I have used ES6 classes in this example, but you can adapt it for Angular as well.

class UserDetails {
    key1 = '';
    key2 = {
      Status: false,
      Label: ''
    };
    key3 = {
      Status: false,
      Label: ''
    };
    key4 = {
      Status: false,
      Label: ''
    };
    key5 = '';
    key6 = '';
    key7 = new Date();
}
class MyService {
 userDetails;
 constructor(){
   this.userDetails = new UserDetails();
 }
 populate(){
  this.userDetails.key1 ="foo"
  this.userDetails.key2 = {
      Status: true,
      Label: 'bar'
  };
  return this.userDetails;
 }
 reset(){
  this.userDetails = new UserDetails();
  return this.userDetails;
 }
}
let service = new MyService();
console.log(service.populate());
console.log("***********Resetting************");
console.log(service.reset());

Answer №2

Here is a simple solution that may fit your needs. You can iterate through each key in the UserDetails object and delete the key if its value is not an object:

var UserDetails = {
  key1: '',
  key2: {
    Status: false,
    Label: ''
  },
  key3: {
    Status: false,
    Label: ''
  },
  key4: {
    Status: false,
    Label: ''
  },
  key5: '',
  key6: '',
  key7: new Date(),
};

Object.entries(UserDetails).forEach(([key, value]) => {
  if (typeof value !== "object") {
    delete UserDetails[key];
  }
});

console.log(UserDetails);

Answer №3

To simplify this task, you can utilize the reduce function. Simply set the keys with non-object values or instances of Date to an empty string.

const input = {
    key1 : '' ,
    key2: {
      Status: false,
      Label: ''
    },
    key3: {
      Status: false,
      Label: ''
    },
    key4: {
      Status: false,
      Label: ''
    },
    key5: '',
    key6: '',
    key7: new Date(),
}

const output = Object.entries(input).reduce((accu, [key, val]) => {
    if(typeof val != 'object' || input[key] instanceof Date) {
        accu[key] = "";
    } else {
        accu[key] = val;
    }
    return accu;
}, {});

console.log(output)

Answer №4

If you're looking for a solution, you can follow the advice given by Amardeep Bhowmick, or you have another option of creating a function within your service that will return the desired object. Here is an example of how you can set up this function:

private createObject():any{
    var object = {
            key1 : '' ,
            key2: {
              Status: false,
              Label: ''
            },
            key3: {
              Status: false,
              Label: ''
            },
            key4: {
              Status: false,
              Label: ''
            },
            key5: '',
            key6: '',
            key7: new Date(),

          }
    return object;
}

Simply call

this.UserDetails = this.createObject();
whenever you need to reset the object. You can also use this function to initialize the object for the first time.

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

Difficulty with Bootstrap 4 mobile navbar dropdown feature

<div class="baslik baslik1 baslik2 "> <nav class="navbar bg-light navbar-light navbar-expand-sm sticky-top "> <a href="./index.html" class="navbar-brand"><img src="img/512x512logo.png" ...

Utilizing Google's GeoApi to retrieve users' location data regarding their city and country

I am currently using this code to retrieve the full address information of users function getGeo() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (a) { $("#geoLoc").html("Determining your location. ...

Guide on inserting a new user to the db.json

My database file, db.json, has the following structure: { "users": [ { "id": 0, "isActive": true, "balance": "$2,309.20", "picture": "http://placehold.it/128x128", "age": 26, "accessLevel": "guest", "firstNa ...

Issues with the drop-down menu in the <s:select> element arise when attempting to set the

While utilizing a Map to populate the Struts2 tag <s:select >, I have noticed that when the form is submitted multiple times, a blank line is added at the end of the list. For example, if the Map contains 2 key-value pairs, it displays 3 records and ...

Toggle Vue transitions on and off with a boolean parameter

Is there a way to dynamically disable a transition animation in Vue based on a boolean value? Currently, the animation is enabled with the following code: <transition name="fadeUp"> <div v-if="elIsVisible"> <p>Foo Bar</p> ...

Sharing VueJS router with child component

How do I pass the router to my child component? This is my current router setup: import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) export default function () { const Router = new VueRouter({ mode: ' ...

Detecting Whether a Vue/Vue Router Navigation was Triggered by the Back/Forward Button or a Manual Router Push

When using vue/vue-router, I have set up a watcher on $route that is triggered in two different ways: By clicking back or forward on the browser. When the user interacts with a form. There are watchers on the variables that the form uses, and these watch ...

Tips for retrieving all values included in the <tr> tags within an html <table>

When the checkbox in the fourth column is clicked, I would like to retrieve all values of td. Additionally, I want to determine the smallest value between ID and Optional ID. <table><form method='GET'> <tr> <th>Name</t ...

React is unable to maintain the list during route transitions

I have been working on a project where I input user information into a form and upon submission, it displays the data in a table on the same page. Everything works fine initially, but when I navigate back to the form page after visiting the Home page, the ...

Node.js JSON parser encountering an unexpected undefined error

Whenever I attempt to JSON.parse the string, an error occurs and I receive this message: undefined:1 {"device":"FaclonTest","data":[{"tag":"LATITUDE","value":1903.5091},{"tag":"LONGITUDE","value":07251.0348}]} I'm unsure of where the mistake is. Can ...

Assigning objects in PHP

As a PHP learner, I am seeking assistance with the following PHP Object-Oriented Programming (OOP) code: class x{} $x = new x; $x->name = "Chandan"; class y extends x {} // Inheritance $y = new y; var_dump($x); // object X; Shows Name property va ...

How can I utilize jQuery to add tags in a box?

I have an idea for a feature similar to the Stack Overflow tag insert. My goal is to have a box where I can type in a tag, click 'Add', and see it appear above. Additionally, I want this action to update an array called 'SelectedTags'. ...

Avoid mutating the prop directly and instead, utilize a data or computed property that is based on the value of the prop. The prop that is being mutated in this case is

Help me understand this issue that Vue is displaying, I am not sure what is going on. This is my progress element: <el-progress :percentage="percentCompleted" v-show="uploadingVideo"></el-progress> data() { return{ percentCompleted: 0 ...

Tips on how child component can detect when the object passed from parent component has been updated in Angular

In the child component, I am receiving an object from the parent component that looks like this: { attribute: 'aaaa', attribute2: [ { value }, { value }, { value }, ] } This object is passed to th ...

Tips for sending functions from client to server in Node.js

I'm working with this code snippet: const http = require('http'); const fs = require('fs'); const handleRequest = (request, response) => { response.writeHead(200, { 'Content-Type': 'text/html' ...

Leveraging the @Input Decorator in Angular 2

Check out the Angular 2 component code sample below @Component({ selector: 'author-edit', templateUrl:'./author/edit' }) export class AuthorEditComponent implements OnInit{ @Input() author: AuthorModel; fg: FormGroup; c ...

Struggle with incorporating a file

As part of the login process, I have two options available: easy login and standard login. The easy login requires an employee ID, birthdate, and captcha answer, while the standard login asks for first name, last name, birthdate, and captcha. To facilitate ...

What is the best way to ensure bidirectional text appears correctly when two conflicting languages are combined, ensuring explicit directionality is set?

As I work on localization implementation, I encounter an issue with the directionality of mixed characters on the page. The text content is stored in a json file and inserted into the DOM using a Vue.js template. While individual characters display corre ...

Move the camera in Three.js along a path between two vectors

I created a basic scene and came across a tutorial at to help me move the camera: var timer = new Date().getTime() * 0.0005; camera.position.x = Math.floor(Math.cos( timer ) * 200); camera.position.z = Math.floor(Math.sin( timer ) * 200); However, I n ...

[Nuxt.js/Typescript] Accessing Vuex data in Nuxt.js using Typescript

Hello, I am new to Typescript and I have encountered an issue with setting Objective Data to Vuex store. Here is the Objective data of Users (also known as account). # models/User.ts export interface IUser { email: string | null name: string | null ...