Incorporating the values of JavaScript objects into a global variable

I'm currently developing a bank account program and facing a challenge in adding my direct debits (DDs) into the global variable. When I create new objects using my constructor function and add them into the bank account, only the last created DD is showing up.

My aim is to push all DDs into the bank account.

Here's the code snippet:

// Initializing the bank account with a value of 0
var bankAccount = {};

// Constructor function to create a direct debit with a name and cost
function DirectDebit(name, cost) {
  this.name = name;
  this.cost = cost;
}

// Creating a new direct debit for my phone
var phone = new DirectDebit("Phone", 20);
var car = new DirectDebit("Car", 250);

function addToBank(dd) {
  bankAccount = dd;
}

addToBank(phone);
addToBank(car);

console.log(bankAccount);

This results in:

DirectDebit { name: 'Car', cost: 250 }

Answer №1

Instead of setting the data directly, create a bankAccount array and push the data into it.

var bankAccount = [];
function addToBankAccount (data) {
    bankAccount.push(data);
}

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

Applying styled text to a Node.js chat application

I developed a chat application using node.js which allows users to enter a username and send messages. The messages are displayed in a <ul> format showing "username: message". I was looking for a way to make the username appear bold and in blue color ...

Running a jQuery function that triggers a PHP script when the page

Hi there! I'm currently working on implementing jQuery's ajax feature to call a php script when the page loads. This php script will fetch xml data from a web service URL, parse it, and then display specific parts of it within a div tag on the pa ...

Creating a Pre-authentication service for AWS Cognito using VueJS

Implementation of Pre-Authentication feature is needed in my VueJS application for the following tasks: Validation of ID/Refresh Token to check if it has expired. If the IdToken has expired, the ability to re-generate it using the Refresh Token or altern ...

Middleware functions in Mongoose for pre and post actions are not being triggered when attempting to save

After carefully reviewing the documentation, I am still unable to pinpoint the issue. The pre & post middleware functions do not appear to be functioning as expected. I have made sure to update both my node version and all modules. // schema.js const sch ...

Solving yarn conflicts when managing multiple versions of a package

My software application contains a vulnerability related to a package that has different versions available (1.x, 2.x, 3.x). Since many other packages rely on this particular one as a dependency, updating each one individually is not a viable solution at t ...

Top recommendation for showcasing a numerical figure with precision to two decimal points

Within my function, I am tasked with returning a string that includes a decimal number. If the number is whole, I simply return it as is along with additional strings. However, if it's not whole, I include the number along with the string up to 2 deci ...

Use hyphens instead of spaces in angular js data binding

<form role="form" method="POST" action="{{ url('/roles/save') }}" data-ng-app=""> <div class="form-group"> <label>Page-Title:</label> <input type="text" required value="" data-ng-model="title" name="pag ...

Best practices for updating nested properties in Angular objects

I have a dataset that includes information about fruit prices for different years: { "fruits": [ { "name": "apple", "prices": [ { "2015": 2, "2014": 3, ...

Is there a way to transfer the input value from a textfield in one component to another component in ReactJS?

I have a scenario where I need to pass the value of a text area from one component in reactjs to another. The component's value is stored using a useState hook in the first component, and I want to access it in another component to run a map() functio ...

NodeJS package 'jquery' npm not functioning properly (issue with $.on())

I've successfully installed and loaded jquery by using $ = require('jquery'); However, when I attempt to utilize it: app.get('/', function (req, res) { res.render('index'); $.on('ready', function () { ...

Tips on adding style to your jQuery autocomplete dropdown

I am currently utilizing jQuery autocomplete functionality. I have configured it to communicate with a service and retrieve records: <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1 ...

What is the best way to extend the width of an element within a Bootstrap column beyond the column itself?

Apologies for any language errors, but I have a query regarding Bootstrap. I am currently working on making a website responsive and I have a row with 4 columns set up like this: The "seeMore" div is initially hidden and on clicking the boxToggle element ...

Modifying the input placeholder color with ng-style

I am working on setting the color of my input placeholder using a dynamic color defined in a $scope variable in my controller for my HTML code. The $scope variable is structured as follows: $scope.primaryColor={"color":colorVar}; //colorVar represents th ...

Ways to replace CSS classes created using makeStyles

To clarify, my development environment is using MUI version 4.12.3. Inside file A, I have a simplified code snippet for a functional component, along with the usage of makeStyles to style a JSX element within the return statement (not displayed here). Ever ...

Load Bootstrap CSS file externally on a website dynamically

Although my knowledge of JavaScript is limited, I am the recipient of a small web application from a friend that is being utilized by multiple companies. As each company requires specific modifications in the appearance and CSS of certain webpages, it can ...

Using JavaScript to create a tree structure with hierarchical organization in JSON

Having some trouble converting a nested hierarchical tree from a JSON array. Looking to create a hierarchical tree structure from the provided JSON data. Below is the data: [{ "_id" : "59b65ee33af7a11a3e3486c2", "C_TITLE" : "Sweet and Snacks", ...

Searching for values within an array of objects by iterating through nested arrays to apply a filter

Having trouble returning the testcaseid from an array to this.filteredArray Able to fetch header value and all values of the array when the search word is empty. Seeking assistance with iterating through the testcaseid and header on the search input fiel ...

There is no 'depto_modules.length' property in this row. How should I go about fixing this issue?

I have a table set up to display data from an associated table. The functionality is working fine, but I keep seeing a warning message when I apply certain filters: The warning states that the property depto_modules.length does not exist in the row. It ad ...

Is there a way for me to create a clickable link from a specific search result retrieved from a MySQL database using an AJAX

Currently, I am attempting to create an ajax dropdown search form that provides suggestions based on results from a MySQL database. The goal is for the user to be able to click on a suggestion and be redirected to the specific product. The code I am using ...

AFrame: keeping an element's world position and rotation intact while reparenting

I am attempting to reassign a child element (entity) to another parent while preserving its position, rotation, and possibly size in the scene. Ideally, I would like to implement a component (let's call it "reparent") that can be added to an entity to ...