Skip to content

Instantly share code, notes, and snippets.

@RR-Helpdesk
Last active June 10, 2023 12:22
Show Gist options
  • Save RR-Helpdesk/6aa5e1022453ab216b90986cd08a46d2 to your computer and use it in GitHub Desktop.
Save RR-Helpdesk/6aa5e1022453ab216b90986cd08a46d2 to your computer and use it in GitHub Desktop.
# # #* *JAVASCRIPT: CODE SNIPPETS** For the data geeks out there, here's a cheatsheet of JavaScript code snippets that can come in really handy for formatting data from different sources or transforming it into a usable format.
#### DEEP COPY AN OBJECT
```js
var copiedObj = JSON.parse(JSON.stringify(obj));
```
Explanation: In JavaScript objects, copying an object variable results in copying only the reference to the same object. Hence, any changes to its embedded key-pair values result in changes made to the original object variable as well.
```js
var obj = { a: 1, b: 2 };
var copiedObj = obj;
copiedObj.a = 2;
console.log(copiedObj); // {a: 2, b: 2}
console.log(obj); // {a: 2, b: 2}
```
To prevent changes from being made to the original object, consider using the following to deep copy an object variable instead (note that changes made to the new object variable no longer change elements in the original object):
```js
var obj = { a: 1, b: 2 };
var copiedObj = JSON.parse(JSON.stringify(obj));
copiedObj.a = 2;
console.log(copiedObj); // { a: 2, b: 2 }
console.log(obj); // { a: 1, b: 2 }
```
#### REMOVE OBJECT KEY AND VALUE PAIR
```js
delete obj[keyValue];
```
Explanation: At times when you wish to remove a key-pair value from an object completely, rather than iterate through the object and assigning it to another empty object ( {} ), simply use the delete keyword:
```js
var obj = { id: 1, name: "ABC Primary School", category: "school" };
```
// assuming keyValue = "category":
````js
delete obj["category"]
````
// obj now becomes { id: 1, name: "ABC Primary School" }
#### REMOVE THE LAST ELEMENT OF THE ARRAY
```js
arr.pop();
```
Explanation: Similar to point 4, rather than iterate through the entire array and transfer all elements excluding the last element into a newly initialised array ( [] ), simply use pop:
```js
var arr = ["first", "second", "third", "forth"];
arr.pop();
```
// result of arr is: ["first", "second", "third"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment