Skip to Content
Technical Articles
Author's profile photo FIRAT ASAN

Cloning an Array in SAPUI5 or Fiori Projects with JavaScript

Hello,

I am working on the function of a button in a Sapui5 project. I wrote my codes without testing them first and realized a little late that the button’s function was not working properly. As the code got longer, it became difficult to find where the error was made. However, I realized that the arrays I created in a simple way affected each other. I thought I made a simple assignment mistake, but I was surprised that the assignments for the Arrays were correct. It was even difficult to find where the change occurred. It was obvious that there was a mistake for arrays containing objects, and in my research on the internet and blogs, the following methods were presented as solutions:

  1. JSON.parse and JSON.stringify method
  2. Assigning values with For loops
  3. Array.slice() method
  4. spread operator (clonedArray = […orginalArray]) method
  5. Array.concat() method

But they are not worked.

I have solve it with these codes. And i want to share with that blog post.

//Cloning arrays:
			function deepCopyArray(arr) {
				if (Array.isArray(arr)) {
					var copy = [];
					for (let z = 0; z < arr.length; z++) {
						copy[z] = deepCopyArray(arr[z])
					}
					return copy;
				} else if (typeof arr === 'object' && arr !== null) {
					var copy = {};
					for (var key in arr) {
						if (arr.hasOwnProperty(key)) {
							copy[key] = deepCopyArray(arr[key]);
						}
					}
					return copy;
				} else {
					return arr;
				}
			}

			if (editedInsList.length == 0) {
				editedInsList = deepCopyArray(defaultInsList);
				editedInsList2 = deepCopyArray(defaultInsList);
			}

I hope it was a useful sharing. Thank you for taking the time to read.







Assigned Tags

      2 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Wouter Lemaire
      Wouter Lemaire

      You can also find a good explanation on deep copies here: https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy

      not really ui5 related in my opinion…

      Author's profile photo FIRAT ASAN
      FIRAT ASAN
      Blog Post Author

      Thank you for reading my blog post. But i have written which methods that i have tried. One of them is JSON.parse and JSON.stringify method but its not working for my case. My Array is a complex type. Maybe that is the reason.