JavaScript, connecting to added element

Is there a way to add an element to an array and then modify it later on?

//Create a new object
var ob = new User({login:"Max", age:22});
//Array of existing elements
var users = array[..] //assume the length is 5
//Add the new object to the array
users.push(ob);
//Update the object's data and reflect the changes in the array element (save data to server, retrieve ID of saved element)
ob.age = 33;

What would be the best approach to achieve this?

Answer №1

Your provided solution should function perfectly as it stands.

Within JavaScript, arrays store references, meaning that the object stored is identical to the one you inserted using push.

If you were to reassign the variable ob to a new object, you can still retrieve the last element by using users[users.length-1]

Answer №2

Feeling drawn to you may not be right, but here are the steps you can take:

  1. Locate the specific item in need of location modification within the array.
  2. Create a fresh object to reset the pertinent values.
  3. Integrate the freshly created object back into the array.

Answer №3

ob represents an object, and the variable users contains a pointer to that object ob. Therefore, the variable users has already undergone modifications. If you are utilizing a database (such as mongoDB), it is only necessary to persist the changes made to the variable users in the database.

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

Creating a custom Angular HTTP interceptor to handle authentication headers

Necessity arises for me to insert a token into the 'Authorization' header with every HTTP request. Thus, I created and implemented an HttpInterceptor: @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(public ...

Determine the status of all jqXHR requests within an array to confirm completion

My goal is to execute a block of code once all the jqXHR elements in an array have completed, whether they have succeeded or failed. For the full code, you can check it out here: http://jsfiddle.net/Lkjcrdtz/4/ Essentially, I am anticipating the use of t ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

Revamp responsiveness in bootstrap 3 for printing with @media queries

My goal is to disable the responsive features of bootstrap when the event javascript:print() is triggered. This way, I want my webpage to maintain the column grid layout that I have defined, regardless of screen size. One solution suggested in this answer ...

What could be causing the Firebase email verification to result in a 400 error?

I've been struggling to implement email verification in my React website. Every time I try to use the sendSignInLinkToEmail function, I keep encountering this error: XHRPOSThttps://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=XXXXXXXXXXX ...

Controlling the Class Attribute in a <td> Element with JavaScript Upon Click Event

I am currently grappling with a situation involving a table with 5 <td> elements. By default, these <td> are red in color. If the user clicks on one of them for the first time, it changes to blue. Subsequent clicks turn it orange and then back ...

Angular Resolve Upon Application Reloading

Is there a way to postpone the initialization of my Application Controller (similar to using the 'resolve' attribute in the router) when reloading a page? Or more importantly, how can I delay the rendering of the view until my controller has succ ...

What is the best way to completely eliminate a many-to-many relationship with a custom property?

I have encountered a situation where I am utilizing an entity setup similar to the one explained in this resource. The problem arises when I try to remove entries from post.postToCategories. Instead of deleting the entire row, TypeORM sets one side of the ...

What steps should I take to export a function from a React functional component in order to create a reusable library?

Currently, I am in the midst of developing a React component library and one of my components contains a function that I want to export. The purpose of the addParticle function is to enable users of the library to dynamically insert particles into a cont ...

AngularJS validation for minimum character count prevents character overflow

Encountering an unusual "issue". I've set up a form with a textarea that has both a minlength and maxlength validation. In addition, there's a straightforward character count displayed: <textarea ng-trim="false" ng-model="form.text" minlengt ...

The JQuery .replaceWith method exclusively offers unprocessed HTML content

I'm experiencing a minor issue with my ajax response where it returns raw html and does not execute any scripts, resulting in the jquery ui scripts not being executed. Here are some details: I am currently working with ASP.NET MVC and I need to comm ...

The styles from the npm package are not being properly applied to the class

After creating my react npm package using webpack, I encountered an issue where the styles from the package were not being applied to classes when installed in my react project. I used style-loader in my webpack configuration, but kept getting errors sayin ...

What is the best way to dynamically select and deselect radio buttons based on a list of values provided by the controller?

I am currently working on implementing an edit functionality. When the user initially selects a list of radio buttons during the create process, I store them in a table as a CSV string. Now, during the edit functionality, I retrieve this list as a CSV stri ...

Evaluating the functionality of express.js routes through unit testing

Just dipping my toes into the world of express and unit testing. Take a look at this code snippet: const express = require('express'); const router = express.Router(); const bookingsController = require("../controllers/bookings"); router .r ...

Interactive Autocomplete Component

I am encountering issues with passing dynamic data to my autocomplete angularjs directive, which is built using jQuery-UI autocomplete. Below is the current code I am working with: HTML: <div ng-app="peopleApp"> <div ng-controller="indexCont ...

The Ajax request is successfully looping through multiple files, however, it is not properly sending them to the server. As a result, only one file

I have been working on an ajax request that successfully retrieves information about files, such as the number of files, their names, and looping through them. Now, I am faced with the challenge of saving these files to a local folder on my computer. I hav ...

Can someone explain the meaning of [Object: null prototype] when using url.parse() with nodeJS?

I am currently diving into learning nodeJS for my project and still getting the hang of how nodeJS works. I have a question regarding a confusing issue I encountered while trying to use the .query method with url.parse(request.url, true). I keep seeing an ...

Is it possible to attach an onclick event to modify a data point in Chart.js?

Currently using chartjs for a small project and facing some challenges with editing data points. Is there a built-in function in this library that allows me to bind an onclick event for displaying a pop-up and removing the point? This is what I am lookin ...

Contrasting React Context and the JavaScript window object

React introduces a feature known as Context, which provides a method for storing globally accessible values without the need to pass them down as props. I am curious about the benefits of using React's Context compared to simply storing values on the ...

Using jQuery to align a div element to the top of the viewport

Is there a way to keep the #lightbox div positioned at the top of the viewport consistently? $(document).ready(function(){ $('.mehr').click(function() { $("body").css("overflow", "hidden"); $('#lightbox').css({'visibil ...