Reputation: 637
I have a js object like
[{"name":"John","group":"t1..." .....}]
so to create new user from same t1, I loop through the obj using
var new_user;
for(var i=0; i<users.length; i++) {
if(users[i].group === 'group name goes here') {
new_user = users[i];
break;
}
}
then is simply push it using users.push(new_user);
then I try to change the just the name using
var l = users.length - 1; users[l].name = 'Jack';
it changes the name for the all the users.
[{"name":"Jack","group":"t1..." .....},{"name":"Jack","group":"t1..." .....}]
I know I am doing something wrong. I appreciate any help.
Upvotes: 1
Views: 67
Reputation: 14614
@Haneev's answer gives the concept of why the name
of all users
elements was changed by your code. Below is a code example of how you copy users[i]
using slice method
var users = [{"name":"John","group":"t1"}];
var new_user;
for(var i=0; i<users.length; i++) {
if(users[i].group === 't1') {
// make a copy of users[i] and assign to new_user
new_user = users.slice(i);
break;
}
}
// add new_user to users
users.push(new_user);
var l = users.length - 1;
users[l].name = 'Jack';
alert(users[0].name); // this will display John
alert(users[1].name); // this will display Jack
Working demo: http://jsfiddle.net/hkLkkepo/
Upvotes: 1
Reputation: 775
Problem here is that you assign the a new variable name to an old object. That is a reference and not a copy of the object. new_user = users[i]
creates an reference that new_user
is linked to users[i]
. You have to copy the users[i]
object, in order to only change the new_user
. Underscore has a copy/clone function that you can use.
Upvotes: 7