Deep copying in Javascript without resorting to JSON or using variable assignments


I'm seeking help with a JavaScript question: I recently attempted some challenging exercises from a JavaScript book I'm studying, and I'm feeling stuck. The task at hand is to create a deep copy function using *only ES6* arrow functions without relying on any JSON methods or variable assignments. Additionally, the author recommends avoiding scopes by not using {} brackets. Can anyone provide me with hints or tips on how to tackle this?

Answer №1

To create a recursive function that takes a value and returns a copy of it, we need to check the type of the value first. If the value is an Array, we should return a new Array in which every element is recursively copied using the same function. If the value is an Object, we must generate a new Object with copies of its properties. For primitive values like strings, numbers, or booleans, we can simply return the value.

It's worth noting that although writing the code without variable assignments and curly brackets might be interesting for learning purposes, it can make the code less readable. In a professional setting, I would never write code this way:

const deepCopy = v =>
  // Check if it's an Array
  v instanceof Array ?
    // Map each value to its copy
    v.map(deepCopy) :
    // If not, check if it's a non-null Object
    (typeof v === "object" && v !== null) ? 
      // Create a new Object with copied property values
      Object.entries(v)
            .reduce((acc, [k, v]) => ({ ...acc, [k]: deepCopy(v) }), {}) :
      // Otherwise just return the value
      v;

console.log(deepCopy({foo: 'bar', arr: [{baz: 42}, true]}));
console.log(deepCopy("Hello world"));
console.log(deepCopy(["a", "b", null]));

Answer №2

If you want to extract arrays of keys and values from an object using Object.keys() and Object.values(), then iterate through them to assign those items to a new object, give this a try:

let exampleObject = {key1: 'value1', key2: 'value2'};

let extractedKeys = Object.keys(exampleObject);
let extractedValues = Object.values(exampleObject)

console.log(extractedKeys, extractedValues)

let newObject = {};

for( let index = 0; index < keys.length; index++ ){
    newObject[extractedkeys[index]] = extractedvalues[index] 
}

console.log(newObject);

newObject.key1 = 'modified';

console.log(newObject);

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

Adjusting the size of SVG rectangle shapes within a group container

I'm struggling to resize an SVG in my website. It is located within the header of the site, and previously I was resizing a regular image like this: $("#block_175 img").height($("#header").height() / 2); Now that I switched to using an SVG, I have b ...

Firefox only loads images and jquery after a refresh of the page

Upon initially accessing my site after clearing the cache (a jsp page from a spring app), I noticed that the images and styles were not being applied. However, upon refreshing the page (ctrl-r), everything loaded perfectly. In Firefox's console outpu ...

Differences between Arrow function and regular function when used in Array.map()

While working on some JS challenges, I observed that when using arrow functions, the result is as expected. However, when I try the same code with a regular function, it doesn't work. Can someone please explain the difference or point out if there is ...

What is the best way to reset everything back to its original position by clicking anywhere on the screen except for the specified div?

Is there a way to make the entire screen reset to its original state with just one click anywhere on the screen, rather than having to click a specific button? Any assistance on this matter would be greatly appreciated. Thank you! JQUERY CODE $(".readNow ...

The PHP script's header() function is failing to execute

Recently, I encountered an issue with my JavaScript code that calls a backend PHP script using AJAX. The main function of the AJAX request is to send user login data (username and password) to the PHP script, which in turn queries this information on the S ...

issues with the handler not functioning properly in html and javascript

<form method="post" action="."> <label class="input-label">Enter Your First Name</label><input field="first_name" class="input-edit" maxlength="30" type="text" value="{{ user.first_name }}" /> <label class="i ...

Utilize the passed value within the $scope.$on function

When I use broadcast to send data, I encounter an issue. Here is the code snippet: $rootScope.$broadcast('myEvent',{ data:"value" }); Now, here is my 'on' code: $scope.$on('myEvent', (event, args) => { $scope.da ...

What is the process for including paths as parameters in jvectormap?

Can you assist me with a simple question regarding jvectormaps? How can I pass paths as parameters using this plugin? $('#worldMap').vectorMap({ map: 'world_mill_en', backgroundColor: "transparent", ...

Looking to crop a canvas without changing its dimensions using jQuery

I'm currently working on a project that involves overlaying two images; one uploaded by the user and the other a default image. However, I am facing an issue when the uploaded image is a rectangle instead of a square, causing the canvas to resize it. ...

The scraping tool from Snipcart encountered issues while trying to capture product data in a Next.js

I am encountering an issue with Snipcart while using it in a Next.js app integrated with Strapi. The error message I receive when processing a payment is as follows: A 'cart-confirmation' error occurred in Snipcart. Reason: 'product-craw ...

Wondering how to optimize FullCalendar for mobile and touch events?

I am looking to incorporate a drop event feature into the mobile version of fullcalendar. To achieve this, I am utilizing Jquery UI Touch Punch. After researching on various platforms such as Stack Overflow 1, Stack Overflow 2, Stack Overflow 3, Stack Ove ...

`Inability of ngmodel to bind integer values on select element`

From the service, I will be receiving an integer as the selected value and need to send it back as an integer. Please refer to the code in this Plnkr link. <!-- Working --> <div ng-init="selectedvalue = '3'"> <select ng-model= ...

Show JSON information from a jQuery post request

Greetings, I am currently working on implementing a login script using Ajax. My objective is to retrieve and display data such as email and username, and then store it in local storage. Although I can successfully obtain the data in JSON format, I want to ...

Using node.js version 10.0.0 to tinker with gulp

I was working on a node.js api project that functioned perfectly with node.js v8.1.4 & npm v5.0.3. However, upon transitioning to node.js v10.0.0 & npm v5.6.0, I encountered the following error: [email protected] ecosystem E:\opensource& ...

Do we always need to use eval() when parsing JSON objects?

<!DOCTYPE html> <html> <body> <h2>Creating a JSON Object in JavaScript</h2> <p> Name: <span id="jname"></span><br /> Evaluated Name: <span id="evalname"></span><br /> <p> <s ...

Is there a way to submit two forms using just one button?

I have a unique challenge where I need to submit 2 forms using just one button within the Spring MVC framework. Here is the structure of my JSP page: <form:form id="form1" method="POST" modelAttribute="employee" ...

angular js using ng-table in a simple example

I am currently utilizing meteor and attempting to implement the basic example provided on the ng-tables site. However, I am experiencing an issue where only the filters and sort boxes are displayed, but not the data itself. <body ng-app="myApp"> & ...

Setting the Datetimepicker to be used with every input field

I currently have four textboxes identified by their unique ids: title, sdate, edate, and pdate. My goal is to assign a Datetimepicker to the textboxes that contain the word 'date' in their id. This means I want the Datetimepicker to be assigned ...

Having trouble with the $.get function in AJAX with Rails 4? It seems

After working with Rails for a few years, I decided to dip my toes into the world of AJAX. With a Rails 4 app in hand, I'm currently testing out some functions. My end goal is to reload a partial on the edit page located at app/views/stories/edit.html ...

What could be the reason for the lack of error handling in the asynchronous function?

const promiseAllAsyncAwait = async function() { if (!arguments.length) { return null; } let args = arguments; if (args.length === 1 && Array.isArray(args[0])) { args = args[0]; } const total = args.length; const result = []; for (le ...