JS object copying (deep copy and shallow copy)

JS object copying (deep copy and shallow copy)

1. Shallow copy

1. Object.assign(target,source,source...)

a. Supports multiple object replication

b. If the source and target attributes are the same, the source will copy the target attributes

c. Target can only be an Object object

var obj = {a:1,b:2}
undefined
Object.assign({c:3},obj)
{c: 3, a: 1, b: 2}
obj
{a: 1, b: 2} 
Compatibility writing if (Object.assign) {//compatible} else {//incompatible}

2. Spread operator

Supports copying multiple objects to one object"

var obj1 = { foo: "foo" };
var obj2 = { bar: "bar" };
 
var copySpread = { ...obj1, ...obj2 }; // Object {foo: "foo", bar: "bar"}
copySpread 
{foo: "foo", bar: "bar"}
var obj = {a:1,b:2,c:3}
var objs = {...obj}
objs
{a: 1, b: 2, c: 3}
objs.a=10
10
objs
{a: 10, b: 2, c: 3}
obj
{a: 1, b: 2, c: 3}

2. Deep Copy

1. Use object serialization JSON.stringify() and JSON.parse()

Note: This method only works if the original object contains serializable value types and does not have any circular references. An example of a non-serializable value type is a Date object - JSON.parse can only parse it into a string and cannot parse it back into its original Date object or an object whose property value is a function.

var obj = {a:1,b:[1,2,3],c:{e:3},bool:false}
undefined
var objs = JSON.parse(JSON.stringify(obj))
undefined
objs
{a: 1, b: Array(3), c: {…}, bool: false}
objs.bool = true
true
objs
{a: 1, b: Array(3), c: {…}, bool: true}
obj
{a: 1, b: Array(3), c: {…}, bool: false}

2. Use recursion to judge object properties

function deepClone(obj) {
  var copy;
 
  // If obj is null, undefined or not an object, return obj directly
  // Handle the 3 simple types, and null or undefined
  if (null == obj || "object" != typeof obj) return obj;
 
  // Handle Date
  if (obj instanceof Date) {
    copy = new Date();
    copy.setTime(obj.getTime());
    return copy;
  }
 
  // Handle Array
  if (obj instanceof Array) {
    copy = [];
    for (var i = 0, len = obj.length; i < len; i++) {
        copy[i] = clone(obj[i]);
    }
    return copy;
  }
 
  //Handle Function
  if (obj instanceof Function) {
    copy = function() {
      return obj.apply(this, arguments);
    }
    return copy;
  }
 
  //Handle Object
  if (obj instanceof Object) {
      copy = {};
      for (var attr in obj) {
          if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
      }
      return copy;
  }
 
  throw new Error("Unable to copy obj as type isn't supported " + obj.constructor.name);
}

The above is the details of JS object copying (deep copy and shallow copy). For more information about JS, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of shallow copy and deep copy of js objects
  • Two methods of deep copy and shallow copy of JavaScript array
  • JavaScript basics: shallow and deep copying (shallow and deep copying)
  • Detailed explanation of code for implementing shallow copy and deep copy in JS
  • In-depth understanding of javascript deep copy, shallow copy and circular reference
  • Detailed examples of JS assignment, shallow copy and deep copy (deep and shallow copies of arrays and objects)
  • Analysis of the principles and implementation methods of JS shallow copy and deep copy
  • Detailed explanation of JavaScript deep copy and shallow copy
  • Detailed explanation of JS deep copy and shallow copy
  • In-depth explanation of js deep copy and shallow copy

<<:  Command to view binlog file creation time in Linux

>>:  Summary of Linux user groups and permissions

Recommend

Sharing some wonderful uses of wxs files in WeChat applet

Table of contents Preface application Filters Dra...

Tutorial on installing AutoFs mount service under Linux

Whether it is Samba service or NFS service, the m...

Defining the minimum height of the inline element span

The span tag is often used when making HTML web p...

Implementation of React virtual list

Table of contents 1. Background 2. What is a virt...

Writing daily automatic backup of MySQL database using mysqldump in Centos7

1. Requirements: Database backup is particularly ...

Detailed explanation of MySQL startup options and system variables examples

Table of contents Boot Options Command Line Long ...

Summary of new usage of vi (vim) under Linux

I have used the vi editor for several years, but ...

Complete steps to build a squid proxy server in linux

Preface This article mainly introduces the releva...

JavaScript canvas to achieve raindrop effects

This article example shares the specific code of ...

How to operate Linux file and folder permissions

Linux file permissions First, let's check the...

Detailed tutorial on installing mysql on centos 6.9

1. Confirm whether MySQL has been installed. You ...

React Native startup process detailed analysis

Introduction: This article takes the sample proje...

JavaScript counts the number of times a character appears

This article example shares the specific code of ...

Solution to Docker's failure to release ports

Today I encountered a very strange situation. Aft...