Clear an object's attributes

Is there a more efficient way to handle this code?

At the start of my game, I set up a variable to hold all new game information.

var newGameInfo = {
   players: [],
   playersList: [],
   enemies: [],
   enemiesList: [],
   drops: [],
   dropsList: [],
   attacks: [],
   attacksList: [],
   LVL: null
}

Later on, I clear out this variable by using the following code.

    Object.keys(newGameInfo).forEach(key => {
        if(Array.isArray(newGameInfo[key])) {
            newGameInfo[key] = [];
        } else if(typeof newGameInfo[key] === 'number' && key !== 'LVL') {
            newGameInfo[key] = 0;
        }
    });

I would appreciate any tips or suggestions! This code seems overly verbose for such a simple task.

Answer №1

  1. Wrap it in a function
  2. Who even cares about the state if you're just going to overwrite it anyway--ditch the if statements
  3. If you're simply overwriting, why bother with splicing? Just overwrite directly.

Code

var initializeGameInfo = function () {
        return {
            players: [],
            playersList: [],
            enemies: [],
            enemiesList: [],
            drops: [],
            dropsList: [],
            attacks: [],
            attacksList: [],
            LVL: null
        }
    },
    gameInformation = initializeGameInfo();

// game logic


//reset everything
gameInformation = initializeGameInfo();

Answer №2

Rather than using splice to clear the array, you can simply set its length to 0 for the same result:

newGameData.players.length = 0;

If you want to reset the entire state in one go, you can do something like this:

Object.keys(newGameData).forEach(function(key) {
    // loop through the properties of newGameData
    if (Array.isArray(newGameData[key])) {
        // if it's an array, empty it without removing the object itself
        newGameData[key].length = 0;
    } else {
        newGameData[key] = null; // set non-array properties to null
   }
});

Answer №3

The simplest way to handle this is by encapsulating the initialization logic in a function and then using the returned value when starting or resetting the game.

function initializeGame() {
  return {
    players: [],
    playersList: [],
    enemies: [],
    enemiesList: [],
    drops: [],
    dropsList: [],
    attacks: [],
    attacksList: [],
    level: null
  }
}

var gameData = initializeGame();
console.log('Game information:');
console.log(gameData);

console.log('Playing the game...');
gameData.level = 1;
gameData.players.push('Player 1');
gameData.enemies.push('Easy Enemy');

console.log('Updated game information:');
console.log(gameData);

console.log('Resetting the game');
gameData = initializeGame();

console.log('Game information after reset:');
console.log(gameData);

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

Node.JS is flagging a TypeError with the message [ERR_INVALID_ARG_TYPE]: The argument provided for "path" must be a string

As a newcomer to Node.js, I recently embarked on developing a basic movie API application using node.js. By utilizing express-generator, I initiated the app creation process. However, I encountered an error that has proven difficult for me to resolve. In ...

When working with arrays in a programming loop, is it better to assign the value to a variable or access it directly?

When facing a complex for loop with lots of operations, what is the most efficient way to iterate through it? for ($i = 0; count($array) > $i; $i++) { $variable = $array[$i]; $price = $variable->price; OR $price = $array[$i]->price; } T ...

Establishing the controller to set the default order

Would appreciate some assistance with what may appear to be a beginner's question, please? This is the HTML code I'm working with: <!doctype html> <html> <head> <title>Starting Angular</title> </head> < ...

Steps to modify the border width upon gaining focus

I am struggling to adjust the border width when my input box is focused. Currently, it has a 1px solid border which changes to a 2px different color solid border upon focus. However, this change in border width is causing the containing div to shift by 1px ...

Tips for implementing cacheable JSON in HTML

Is there a way to access the data stored in an HTML5 file, specifically in the header section like this: <script type="application/json" src="data.json"> Many have recommended using $.get("data.json"), but that requires loading the data each time. ...

"Enhance your Highcharts experience with dynamic visualization and maximize the number of

When creating dynamic highcharts, I utilize the series.addPoint method. While it successfully adds points, the chart does not move as shown in this example - jsfiddle. This results in potentially having 100 points on the screen. How can I limit the displ ...

How to retrieve a particular value from a multidimensional array

How can I access a specific branch in a multi-dimensional array? Consider the following array: $newarr= Array ( "Tommy" => Array ( Array ( "a" => 25, "b" => 304, "c" => 9277 ), Array ( "a" => 25, "b" => 4, "c" => 23 ) ) , ...

arrange object array in descending order based on an object's numerical value within it (using Angular-Typescript)

Looking for assistance with sorting an array of user objects based on their scores. Each user object contains properties like userId, userName, and score. My goal is to create a leaderboard where the user with the highest score appears at the top, followed ...

Accessing index.html via file:// from Vue-cli template

Whenever I execute the npm run build command using this Vue-cli template, it displays this message: Hint: The built files are designed to be served over an HTTP server. Attempting to open index.html via file:// will not function correctly. Therefore, the ...

What is the best way to update a Bootstrap Toggle with a dynamic value?

When performing an update action, the user can click on an element in a table and change the value by toggling a bootstrap toggle. However, I am unsure of how and where to apply this change. Here is the code snippet: Initially, the user clicks on the ele ...

Is it possible to eliminate the default placeholder text from Safari browser?

My goal is to design a form that includes date and time input fields. The placeholder text should move up by X pixels when the user clicks on the field. While the form appears fine in Chrome, there seems to be an issue with overlapping form fields in Safa ...

A guide to embedding arrays within arrays in Objective-C

In my iOS application, I am creating multiple mock databases. One of these databases needs to have a mutable array within another mutable array. Specifically, I have BlockParties which contain a list of Trucks as one of their attributes. Currently, this i ...

Ways to utilize a string as an object?

Hey there! I'm just getting started with software development and currently working on an application using React Native. The backend is sending me a large data set, but here's a snippet of it. My challenge is that I want to access the first ele ...

Interpreting an undefined HTTP GET request within a Node.js server

I am encountering an issue within my Node.js application. When I send an http get request through an ajax call on the client-side, the server-side does not recognize the request data and returns an "undefined" error message. This problem is puzzling to me ...

Transmit information to Flask server using an AJAX POST call

I'm completely new to Ajax requests. I'm trying to send data from a webpage to my Flask backend using an Ajax request, but I can't get anything to show up in the backend: Here is the request code I am using: function confirm() { cons ...

When the form is submitted, any blank inputs and their corresponding hidden fields will be disabled

I created a form that has multiple input fields, and users have the option to enter values or leave them blank. Each input field is accompanied by a hidden input field which contains a specific id unique to the corresponding visible input field. To disable ...

A type guard for generics in TypeScript

I'm dealing with a variable that can be either of type C1[] or C2<C1>[]. How can I create a type guard for this variable? interface C<T>{ key: string; secret: T; } private isC(d: Foo[] | C<Foo>): d is C<Foo>[] { ret ...

How to simultaneously define multiple variables in MATLAB

Is there a way to simultaneously define multiple variables in a matrix using MATLAB? a = 1 b = 2 c = 3 I want to achieve the following: a = 1 b = 2 c = 3 Instead of directly assigning values like above, I tried making use of matrices: x = [a, b, c]; y ...

Is there a way to implement two distinct JavaScript functions - one for desktop and another for mobile - within the same onclick event attribute in an HTML document?

I'm currently working on a responsive HTML page that has versions for desktop and mobile. In order to properly execute specific functions based on the device's screen width, I have two separate functions - one for desktop and one for mobile - bot ...

Transferring Data from Angular Application to Spring Server via Rest Implementation

I am currently facing an issue while attempting to upload a file using Angular and send it to my Spring-based REST backend. I followed the guidance provided in this resource for my Angular service implementation. However, two problems have arisen: The fir ...