I have been having trouble understanding why temp is being affected here. When looking at the console when running this code:
const objectsArray = [
{'id': 1, 'name': 'Erik', 'yearsCompleted': 2, 'status': 'student'},
{'id': 2, 'name': 'Carol', 'yearsCompleted': 1, 'status': 'student'},
{'id': 3, 'name': 'Sarah', 'yearsCompleted': 4, 'status': 'student'}
];
temp = {
actions: objectsArray.map(student => {
if (student.yearsCompleted === 4) student.status = 'wow';
return student
})
}
console.log(temp)
temp2 = {
actions: objectsArray.map(student => {
if (student.yearsCompleted === 4) student.status = 'foo';
return student
})
}
console.log(temp)
console.log(temp2)
I end up getting the following result:
{ actions:
[ { id: 1, name: 'Erik', yearsCompleted: 2, status: 'student' },
{ id: 2, name: 'Carol', yearsCompleted: 1, status: 'student' },
{ id: 3, name: 'Sarah', yearsCompleted: 4, status: 'wow' } ] }
{ actions:
[ { id: 1, name: 'Erik', yearsCompleted: 2, status: 'student' },
{ id: 2, name: 'Carol', yearsCompleted: 1, status: 'student' },
{ id: 3, name: 'Sarah', yearsCompleted: 4, status: 'foo' } ] }
{ actions:
[ { id: 1, name: 'Erik', yearsCompleted: 2, status: 'student' },
{ id: 2, name: 'Carol', yearsCompleted: 1, status: 'student' },
{ id: 3, name: 'Sarah', yearsCompleted: 4, status: 'foo' } ] }
Why is temp in this case being affected? Are we getting a reference to the objectsArray when setting the actions property of temp to the objectsArray.map function? I thought temp wouldn't be affected in this case. Thank you.
That is because student.status = 'foo' changes the actual item in the temp array. You need to make a copy and return it using the spread operator(...) as below.
const objectsArray = [{
'id': 1,
'name': 'Erik',
'yearsCompleted': 2,
'status': 'student'
},
{
'id': 2,
'name': 'Carol',
'yearsCompleted': 1,
'status': 'student'
},
{
'id': 3,
'name': 'Sarah',
'yearsCompleted': 4,
'status': 'student'
}
];
temp = {
actions: objectsArray.map(student => {
if (student.yearsCompleted === 4) {
return { ...student,
status: 'wow'
}
};
return student
})
}
console.log(temp)
temp2 = {
actions: objectsArray.map(student => {
if (student.yearsCompleted === 4) {
return { ...student,
status: 'foo'
}
};
return student
})
}
console.log(temp)
console.log(temp2)