1

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.

7
  • 1
    var l= users.length-1; Commented Dec 2, 2014 at 13:32
  • My bad i missed the -1. Sorry Commented Dec 2, 2014 at 13:35
  • 1
    Are you sure that all of the other elements had name other than Jack before you do users[l].name = 'Jack'? Commented Dec 2, 2014 at 13:36
  • @ekad i am sure all had different names. Commented Dec 2, 2014 at 13:37
  • 2
    It's not that you're doing anything wrong, but how JavaScript handles the values. See stackoverflow.com/questions/518000/… for more details... Commented Dec 2, 2014 at 13:38

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

@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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.