Skip to content

💧 A lightweight JavaScript utility allowing deep copy-by-value of nested objects, arrays and arrays of objects. 💦

License

Notifications You must be signed in to change notification settings

igorskyflyer/clone.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

clone.js

clone.js

A lightweight JavaScript utility allowing deep copy-by-value of nested objects, arrays and arrays of objects.

Development size: 1.06 KB

Minified size: 347 bytes

USAGE

Simple array copy

let firstArray = [1, 2, 3]
let secondArray = clone(firstArray)

secondArray[0] = 5

console.log('firstArray => ', firstArray) // [1, 2, 3]
console.log('secondArray => ', secondArray) // [5, 2, 3]

Complex array (array of objects)

let firstArray = [
  {
    id: '103',
    name: 'Peter'
  },
  {
    id: '214',
    name: 'Eve'
  }
]
let secondArray = clone(firstArray)

secondArray[0].name = 'John'

console.log('firstArray => ', firstArray)
console.log('secondArray => ', secondArray)

Simple object copy

let firstStudent = {
  id: 103,
  name: 'Ben',
  classes: ['Maths', 'Science', 'English language']
}

let secondStudent = clone(firstStudent)

secondStudent.classes[0] = 'Psychology'

console.log('firstStudent => ', firstStudent)
console.log('secondStudent => ', secondStudent)

Nested object copy

let firstStudent = {
  id: 103,
  name: 'Ben',
  subjects: {
    groupDke: {
      science: 'B',
      maths: 'C'
    },
    groupOpe: {
      foo: 'bar'
    }
  }
}

let secondStudent = clone(firstStudent)

secondStudent.subjects.groupDke.maths = 'B'

console.log('firstStudent => ', firstStudent)
console.log('secondStudent => ', secondStudent)

About

💧 A lightweight JavaScript utility allowing deep copy-by-value of nested objects, arrays and arrays of objects. 💦

Topics

Resources

License

Stars

Watchers

Forks