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

Summary of Common Problems with Mysql Indexes

Q1: What indexes does the database have? What are...

How to Use rsync in Linux

Table of contents 1. Introduction 2. Installation...

HTML web page image tag

Insert image tag <IMG> The colorful web page...

React+Koa example of implementing file upload

Table of contents background Server Dependencies ...

MySQL 5.6.33 installation and configuration tutorial under Linux

This tutorial shares the installation and configu...

Detailed explanation of the available environment variables in Docker Compose

Several parts of Compose deal with environment va...

How to implement nginx smooth restart

1. Background During the server development proce...

Vue mobile terminal realizes finger sliding effect

This article example shares the specific code for...

A brief discussion on the optimization of MySQL paging for billions of data

Table of contents background analyze Data simulat...

A brief analysis of React's understanding of state

How to define complex components (class component...

Tips for importing csv, excel or sql files into MySQL

1. Import csv file Use the following command: 1.m...

HTML embedded in WMP compatible with Chrome and IE detailed introduction

In fact, there are many corresponding writing met...

7 interview questions about JS this, how many can you answer correctly

Preface In JavaScript, this is the function calli...