Problem with adding new elements to nested objects and arrays in JavaScript

Here is the code snippet I am working with:

let users2 = [
    {
        _id: 'ab12ex',
        username: 'Alex',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7e737a675f7e737a67317c4e0">[email protected]</a>',
        password: '123123',
        createdAt:'08/01/2020 9:00 AM',
        isLoggedIn: false
    },
    // More user objects here...
];

// Function to sign up new users
const signUp = (username, email, password, isLoggedIn) => {
    let obj = {
        _id: 'ddfcd',
        username: username,
        email: email,
        password: password,
        createdAt:`${date.getDate()}/${date.getMonth()}/${date.getFullYear()} ${exactTime}`,
        isLoggedIn: isLoggedIn
    }
    let arr = [`${users2.length}`, obj]
    let collection = Object.entries(users2)
    collection.push(arr)
    users2 = collection
}

// Sign up new users
signUp('ali','<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8aebe6e3cae7eb63075b">[email protected]</a>','123',false)
signUp('kerem','<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="157e706770785565677a617a73b767a78">[email protected]</a>','456',false)
signUp('johndoe','<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfa5ab8fa5abe1aca4e2">[email protected]</a>','789',true)

When adding a new user, the first one looks fine. However, when adding a second user or more, it seems to convert the array into an object. Here is an example of what occurs.

What could be causing this issue?

Answer №1

Your approach to adding an object to an Array seems overly complex

Simplify by just pushing to users2

const createUser = (username, email, password, isLoggedIn) => {
    users2.push({
        _id: 'ddfcd',
        username: username,
        email: email,
        password: password,
        createdAt: `${date.getDate()}/${date.getMonth()}/${date.getFullYear()} ${exactTime}`,
        isLoggedIn: isLoggedIn
    });
}

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

Angular ngx-translate not displaying image

My Angular application is utilizing ngx-translate to support multiple languages. I am trying to dynamically change an image based on the language selected by the user. However, I am facing difficulty in updating the image when a language is clicked. The ap ...

Combining load and change events in jQuery at the same time

Often times, I find myself needing to attach a behavior to an element both after it has loaded and after a specific event has been triggered (such as "change"). I believe the most efficient approach would be to combine these actions in one line: $('# ...

The localhost of Mongod does not seem to be connecting properly with the 'npm start' command of my program

I'm currently developing a prototype program that handles account registrations, and my approach involves utilizing Node.JS to write JavaScript code that can be utilized on mobile devices. After downloading MongoDB and setting up the data/db director ...

Implement a system in Angular Service that automatically generates user IDs for an array of user inputs

How can I automatically increment the user ID for each new user input and use that value for deletion or updating of specific entries? If a user adds their details as shown in the output picture link below, I want to display the output in a similar format ...

javascript code will continue running even after returning false

Below is the code I am using to validate password matching and make an AJAX call to check if the email exists. The issue that I am facing is that the code continues to execute after returning false from the function emailexist. The emailexist function retu ...

The dayRender function in FullCalendar does not include the cell property definition

Utilizing the fullcalendar.io plugin, I am trying to inject additional HTML into each cell of the calendar. However, when I check the console, I encounter the following error message: Uncaught TypeError: Cannot read property 'append' of undefin ...

Is it possible to simultaneously use the same plugin with various configurations and unique names in Vue?

I'm attempting to utilize the Vue Currency Input plugin, specifically with two different configurations simultaneously: import Vue from 'vue' import VueCurrencyInput from 'vue-currency-input' const options = { globalOptions: { ...

Ensuring consistency between TypeScript .d.ts and .js files

When working with these definitions: https://github.com/borisyankov/DefinitelyTyped If I am using angularJS 1.3.14, how can I be certain that there is a correct definition for that specific version of Angular? How can I ensure that the DefinitelyTyped *. ...

The animation in my jQuery code is not functioning properly following an AJAX request

My animation is working fine after an initial ajax call, but when the user navigates back to the front page, it doesn't run. I'm new to Jquery and could use some guidance on how to fix this issue. I believe the problem might be related to using ...

determining the amount by which a div extends beyond the window's height

My challenge is to have a fixed div appear on top of various background images. The problem arises when this fixed div exceeds the height of the window, causing it not to scroll and resulting in lost content. I've attempted using max-height: 100% and ...

Best method for displaying a div using ASP.NET server controls

There is a concealed div containing ASP.NET server buttons. When I display the content of this div as a modal window on the page using JavaScript by copying innerHTML, the buttons do not trigger server events. Can anyone offer a solution to this issue? ...

Displaying all items in a collection as HTML using Node.js

I am looking to showcase all the items in my mongodb collection as HTML. In the past, I have accomplished this with simpler tasks, such as... router.get('/', function (req, res) { res.render('home', { title: 'Express', u ...

Triggering this function when clicked

I am trying to figure out a way to trigger this code onClick instead of automatically. Can anyone help me with this question? Below is the JavaScript code snippet: $("input[type=radio],button").each(function () { var outputName = $(this).attr("d ...

Steps for implementing AJAX to display a success function and update database results in real-time

I'm struggling with allowing my AJAX call to send data to my PHP file and update the page without a reload. I need the success message to display after approving a user, but their name doesn't move on the page until I refresh. The goal is to app ...

How come the data from the Firebase real-time database is only displaying in the console and not on the page when using Vue.js?

I am encountering an issue while trying to display a value stored in my Firebase Realtime Database using the {{ exams.name }} syntax in Vue. Although I can see the value when I console.log it, it does not render on the page. However, when I attempted the s ...

Strangely glitchy navigation bar using jQuery

Over at this website, there's a top navbar that shrinks using jQuery when scrollTop exceeds 100px. The functionality works as intended, but there's an annoying stutter issue where the navbar starts jumping up and down erratically after slight scr ...

Appending and exporting dynamic arrays in Python

Recently started learning Python and have been having trouble figuring out how to store and update the new values from my output function in an array for exporting. This is what I've come up with, but it doesn't seem very elegant: merit=5 #examp ...

Obtain elements from an array that combine to reach a specific total in pyspark

I need assistance with a PySpark task involving a dataframe containing arrays of double values. These arrays have elements that either individually equal a specific target value, or can be combined to reach the target value. My goal is to extract these v ...

Maintain the aspect ratio of the image while specifying the height in Next.js

Is there a way to set the height of an image in Next.js to 500px while maintaining its aspect ratio? I've been searching for a solution but haven't found one yet. <div className='relative text-center'> <Image ...

"Could you please provide me with further details on how to use sequelize

I recently started working with node js and I used sequelize-auto to generate the models. However, I encountered an error when following the guidance provided in this link https://github.com/sequelize/sequelize-auto. If you need further clarification on th ...