ArthurJ
ArthurJ

Reputation: 839

Unexpected result when attempting to add an object to an array

Just a bit confused as to why the following is occurring:

let groupdetails = {
      groupName: "",
};    
const groupsArray = [];

groupdetails.groupName = 'A'
groupsArray.push(groupdetails)
groupdetails.groupName = 'B'
groupsArray.push(groupdetails)
console.log(groupsArray)

The result I am getting is:

[ { groupName: "B" }, { "groupName": "B" } ]

The result I was expecting was:

[ { groupName: "A" }, { "groupName": "B" } ]

Unsure what I am doing wrong?

Upvotes: 1

Views: 63

Answers (3)

Vishnu
Vishnu

Reputation: 2187

You should create a different reference each time you push an element

let groupdetails = {
      groupName: "",
};    
const groupsArray = [];

groupdetails.groupName = 'A'
groupsArray.push(groupdetails)
groupdetails = {...groupdetails}
groupdetails.groupName = 'B'
groupsArray.push(groupdetails)
console.log(groupsArray)

Upvotes: 1

Vimax
Vimax

Reputation: 11

Remember Arrays, Objects are copied by references, not just by values

a = 'John';
b = a;
console.log(a === b);

Here values are copied to another variable.

obj = {name: 'John'};
newObj = obj;
newObj.name = 'Kate';
console.log(newObj);  // {name: 'Kate'}
console.log(obj)      // {name: 'Kate'}

Here the reference is passed to the other object. So once an object is modified it will be reflected on the other object.

In your case, this will work,

const groupsArray = [];

function addNew(value) {
    return { groupName: value}
}

groupsArray.push(addNew('A'));
groupsArray.push(addNew('B'));
console.log(groupsArray);

Upvotes: 1

Nitheesh
Nitheesh

Reputation: 19986

You are facing issue with Shallow Copy and Deep Copy..

In your case eventhough you were updating the value groupdetails.groupName = 'B', this referes to the same node as the one you pushed initially. You have to creat a new node with spread operater or some thing and update its value and push it again.

In order to achieve your requirement you have to follow something like below mentioned.

let groupdetails = {
  groupName: "",
};
const groupsArray = [];

groupdetails.groupName = 'A'
groupsArray.push(groupdetails);
const newNode = { ...groupdetails };
newNode.groupName = 'B';
groupsArray.push(newNode);
console.log(groupsArray);

Upvotes: 1

Related Questions