Actimele
Actimele

Reputation: 486

JS, link to pushed element

how i can push element to a array and after modify it? Example:

//Here new object
var ob = new User({login:"Max", age:22});
//array of existing elements
var users = array[..] //length for example 5
//pushing to array
users.push(ob);
//here im change element data and would like change it in array element (saving data to server, and return ID of saved element)
ob.age = 33;

How i shoud do it?

Upvotes: 0

Views: 61

Answers (3)

qsona
qsona

Reputation: 67

ob is an object, and users has a reference to the object ob. So, users has already been changed. If you are using some DB (I guess that you are using mongoDB) , you only have to save users to DB.

Upvotes: 0

Feng Ye
Feng Ye

Reputation: 48

It is wrong to like you, but you can to do this:

  1. Find the item you need to modify the location of the array.
  2. Then create a new object, to reset the corresponding values.
  3. Then the newly created object, back into the array.

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96258

What you posted should work as it is.

JavaScript stores references in the array, so the stored object is the same object you pushed.

In case you reassigned the ob variable to a different object, you can access the last element with users[users.length-1]

Upvotes: 1

Related Questions