Exploring the occurrence of immutation within nested arrays inside objects

let myObject = {key : 'Add', array : [0, 2, 3]}

let clonedObject = Object.assign({}, myObject, {array: myObject.array})
clonedObject.array.pop()
console.log(myObject)
console.log(clonedObject)

In the above example, let's say we want to remove an element from the array in clonedObject. Using pop method affects both arrays.

Answer №1

It is crucial to always remember to parse and stringify an object before creating a duplicate,

JSON.parse(JSON.stringify(obj.arr))

An object maintains a reference, so if there are changes made to the child or parent object, both will be affected.

For example, if object a = object b, then modifying object b will impact object a as well.

let obj = {key : 'Add',arr : [0,2,3]}

let obj2 = Object.assign({},obj,{arr :JSON.parse(JSON.stringify(obj.arr))})
obj2.arr.pop()
console.log(obj)
console.log(obj2)

Answer №2

element, it is explained that the issue arises from directly referencing the 'arr' object, which is a reference to an array rather than a copy. To resolve this problem and ensure the correct functionality of the pop() method in your specific case, you can make a copy by modifying obj2 as shown below:
let obj2 = Object.assign({}, obj, { arr : [...obj.arr] })

Answer №3

Object.assign copies objects superficially, meaning nested objects will be linked by reference.

To create a deep clone, you can convert the object to a string and then back again. However, keep in mind that this method may not work well with objects containing functions or circular references as they will be lost in the process of serialization.

let obj = {name: 'John', hobbies: ['surfing', 'skiing']}

let clonedObj = Object.assign({}, obj, JSON.parse(JSON.stringify({hobbies: obj.hobbies})))
clonedObj.hobbies.push('hiking')
console.log(obj)
console.log(clonedObj)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function getSelection().focusNode does not function properly within a specified ID

My current code allows for text to be bolded and unbolded using Window.getSelection(). I found the initial solution here: Bold/unbold selected text using Window.getSelection() It works perfectly without any issues. However, when I tried to modify the code ...

What is the best way to sort search results using various criteria?

Currently, my search filter is only able to filter results based on the 'packageName' field. I now have a requirement to expand this filter to also include the 'dateStart' and 'dateFinish' fields. getters: { filteredPacks: ...

Instructions on how to insert the meta tag with the attribute "http-equiv" set to "REFRESH" and the content "0; URL="somedomain"" into a division on a

Trying to send an ajax request to a page that includes the following meta tag: <meta http-equiv="REFRESH" content="0; URL=https://www.ohterDomain.com/help?nodeId=2&view=content-only"> After making a successful ajax call, the correct content is ...

What is the best way to ensure that the React useEffect hook is triggered only once following a state change

I am brand new to the world of React hooks and I'm facing a specific challenge. Imagine that we have two states, state1 and state2, and we are using the useEffect hook to call asyncFn1 and update state1. My goal now is to wait for a change in state1 ...

Javascript Error: Object Expected

Recently, I have encountered an error in my code that says "object expected" in JavaScript. Surprisingly, the code was working perfectly fine before this issue arose. Strangely, the code is still functioning properly in another solution. Even after making ...

Top location for securely storing information in Angular 8

I have developed a web application using Angular 8. My goal is to secure routes and pages with dynamic access levels. For instance, I want to verify if a user has access to a specific route, and if not, redirect them to the login page. To do this, I cur ...

What could be causing these errors to occur when I use the fetch API?

Having trouble fetching the news API and getting this error message: TypeError: Cannot read properties of undefined (reading 'map'). Any suggestions on fixing this issue? Your help is much appreciated. import React, { Component } from 're ...

Running cy.task after all test suites can be done by adding the task in a

I need some guidance on running cy.task after executing all test suites. I have a file generated at the start of the tests that I would like to remove once they are completed. Regardless of whether any tests passed or failed, I want to trigger cy.task im ...

Mozilla Extension: Run code on initial launch

Currently in the process of building an add-on and looking to implement specific code for its initial run. What I aim to achieve is clicking on the add-on button, navigating through files, and selecting an executable file. This browsing action should only ...

What is the best way to verify a set of requests concurrently before proceeding with their execution or flagging an error?

Below is the code I have written for liking a post on my blog website, which involves three phases. The first phase is adding the liked post to the user's list of liked posts, the second phase is adding the like to the post itself, and the third phase ...

Detecting the specific button that was selected with PHP

I am in the process of developing a website for a production company where, upon clicking on a director's name from the menu, all other menu items disappear and only the selected director's biography and work are displayed. My current challenge ...

Manipulate images in real-time and insert custom text using JavaScript/jQuery

Within my possession is an image depicted above. My objective revolves around dynamically altering the values present at the occurrences of L, A, and B; to achieve this, I must eliminate or conceal L, A, and B while substituting them with numerical equiv ...

Encountered a cyclic dependency in MongoDB when attempting to create an index

I have a dataset structured as shown in the image below: https://i.sstatic.net/eu2ZH.png I am attempting to write a query using $near. However, when trying to create an index for this query, I encounter an error stating "cyclic dependency detected". Below ...

Sending an Angular scope variable to JavaScript

I am working with an angular scope variable that is being used in ng-repeat. My goal is to create a chart that starts from a specific date, ends at another date, and includes a marker for the current day. I am utilizing loader.js for drawing the charts in ...

Selecting Elements in AngularJS with jqLite while Excluding a Specific Element: What You Need to Know

Currently, I am in the process of developing a directive to manage a side menu within a mobile application. The menu opens smoothly with the directive I've implemented, but I am facing a challenge in selecting everything except the menu using jqLite. ...

Unable to activate the navbar toggle feature on Bootstrap 4.0

****I have started working with bootstrap 4.0, but I am facing issues with the navbar toggle functionality. Even after trying to copy code from the official documentation and using the current alpha version of bootstrap, the toggle is not working as expe ...

Having trouble with the jQuery file upload plugin when trying to upload files larger than 5 MB

I successfully incorporated the jQuery file upload plugin into my Codeigniter project to allow users to upload files of any extension. I even managed to increase the upload file size limit to 50 MB. However, I encountered an error when attempting to upload ...

Searching for an item in an array within MongoDB: Tips and techniques

I am attempting to locate the object containing a specific element within an array: Here is my query: router.get('/', function(req, res) { var userSubscribed = req.user.email; db.posts.find({ "SubscriberList": { $elemMatch: userSubscrib ...

Show concealed elements above everything else

I've encountered an issue with my custom dropdown list as it displaces other elements when it appears. I want it to overlay on top of everything else, similar to the default select behavior. Despite trying to set position: relative; and z-index:100;, ...

Leveraging the Power of CSS in Your Express Applications

Struggling to make my CSS links functional while working on localhost. Currently, when I view Index.html on my server, it displays as plain text without any styling. Even after trying the express middleware, the CSS files are still not being served, result ...