I am struggling to understand the behavior of the following lines of code:
// I'd like to keep this value constant
let allObjects = [{value: null}, {value: 'Hello World'}]
// Here is a shorter list of objects matching some criteria
let someObjects = allObjects.filter(object => object.value)
// Here we work with the the values for some of the objects
someObjects[0].value = {hmm: 'test'}
// Kind of expecting allObjects[1].value to be 'Hello World' at this point
// Display all the objects
console.log(allObjects)
And the output:
[
{
"value": null
},
{
"value": {
"hmm": "test"
}
}
]
Here is a codepen.
What I do not understand is when the value of someObjects
is modified it affects the value of allObjects
and expect that allObjects[1].value
will return Hello World
.
Could someone explain to me why this is actually happening and how we are supposed create a sorter version of the array that does not mutate the original array when it is modified?