Home > Web Front-end > JS Tutorial > Learn how to merge and clone objects in JavaScript in one article

Learn how to merge and clone objects in JavaScript in one article

青灯夜游
Release: 2021-06-04 10:39:53
forward
2158 people have browsed it

This article will introduce you to the methods of merging and cloning objects in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Learn how to merge and clone objects in JavaScript in one article

Original and reference values ​​(objects) behave very differently when we want to copy them.

Primitive Value

We assume a variable name has a primitive value associated with it (number, string, boolean, undefined and null) . If we copy this variable name to another variable name2 , any modifications to the original variable will not affect the second variable since they are original values.

let name="前端小智";
let name2= name;
console.log (name, name2); // 前端小智, 前端小智
name="王大冶";
console.log (name,name2); // 王大冶 前端小智
Copy after login

Reference Value

But if we do the same with a reference type value, any changes we make to one variable will also be reflected in the other in a variable because both variables point to the same object.

Array

To copy an array, the slice() method is used to create a new copy of the array. This copy can be modified independently without affecting the original array.

If no arguments are passed, it makes an exact copy of the array, but numbers can also be passed as arguments. If only one number is passed, it will determine the value of the index from which we want to copy, while if two numbers are passed, it will mark the start and end.

// 示例1
const names = ['前端小智', '王大冶', '小力'];
const names2 = names;
console.log(names, names2);
// ["前端小智", "王大冶", "小力"] 
// ["前端小智", "王大冶", "小力"] 

// 示例2
names2[2] = '前端小力';
console.log(names, names2);
//  ["前端小智", "王大冶", "前端小力"] 
//  ["前端小智", "王大冶", "前端小力"] 

// 示例3
const name2 = names.slice();
names[2] = '我是隔壁老智';
console.log(name2, names2)
// ["前端小智", "王大冶", "前端小力"]
//  ["前端小智", "王大冶", "我是隔壁老智"]
Copy after login

Object

The same happens when the reference value is an object, and any modification to one of its properties will affect both variables. To clone an object, use the Object.assign() method, which copies the values ​​of all enumerable properties of one or more source objects to the target object, but this method only copies the values ​​of the object's A shallow copy.

// 示例1
const names = {
  name: '前端小智',
  surname: '隔壁老智'
}

const names2 = names;
console.log(names, names2) // 打印结果是一模一样的

// 示例2
names2.surname ='隔壁老王';
console.log(names, names2)

// {name: "前端小智", surname: "隔壁老王"}
// {name: "前端小智", surname: "隔壁老王"}

// 示例3
const names3 = Object.assign({}, names);
names3.surname = '隔壁老色P';
console.log(names, names3)

// {name: "前端小智", surname: "隔壁老王"}
// {name: "前端小智", surname: "隔壁老色P"}
Copy after login

To make a deep copy of an object, you need to use other methods.

As we said, the Object.assign() method only works as a shallow copy (i.e. when our object has no other objects as properties). In these cases, a deep copy of the object must be made.

Unlike shallow copy, deep copy copies each child object recursively until all involved objects have been copied.

What methods can we use to make a deep copy of an object?

JSON.parse(JSON.stringify(obj))

This method uses JSON.stringify() to convert the object to a string, Then use JSON.parse() to convert it back to an object. This method works for simple objects, but not if the object properties are functions.

const names = {
  name: '前端小智',
  surname: '隔壁老智',
  social: {
    wx: '大迁世界',
    url: 'www.lsp.com'
  }
}
const names2 = JSON.parse(JSON.stringify(names));
names2.social.url = 'www.baidu.com';
console.log(names, names2);

/** 
{
  name: "前端小智"
  social: {wx: "大迁世界", url: "www.lsp.com"}
  surname: "隔壁老智"
}
*/

/** 
{
  name: "前端小智"
  social: {wx: "大迁世界", url: "www.baidu.com"}
  surname: "隔壁老智"
}
*/
Copy after login

Deep Copy

Another very interesting and elegant way to deep copy objects is to use recursive functions.

We create a deepClone(object) function and pass it the object we want to clone as a parameter. Inside the function, a local variable clone will be created, which is an empty object in which every property that will be cloned from the starting object will be added to it.

Specific ideas:

  • If the property is not an object, simply clone it and add it to the new cloned object.
  • If the property is an object, execute the deepClone(value) function again and pass the value of the property (object in this case) as parameter and repeat the same process.
function deepClone(object) {
  var clone = {};
  for (var key in object) {
    var value = object[key];
    if (typeof(value) !== 'object') {
      clone[key] = value;
    } else {
      clone[key]=deepClone(value);
    }
  }
  return clone;
} 

deepClone({value1:1,value2:{value3:2}});
//{value1:1,value2:{value3:2}}
deepClone({value1:1,value2:{value3:{value3b:3}}});
//{value1:1,value2:{value3:{value3b:3}}}
Copy after login

English original address: https://www.ma-o.org/en/programming/javascript/the-javascript-asign-method-to-merge-and-clone -objects

Author: Luigi Nori

Translator: Front-end Xiaozhi

For more programming-related knowledge, please visit: Programming Video ! !

The above is the detailed content of Learn how to merge and clone objects in JavaScript in one article. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template