Multiple ways to merge objects (extremely useful when assigning data to local objects after getting it through an interface)

First: Manual assignment

const obj1 = {
  name: "zs".age: 13};const obj2 = {
  name: "ls".sex: "Female"}; obj1.name = obj2.name; obj1.sex = obj2.sex;Copy the code

This method is the simplest, but it can be a bit tedious to use in everyday projects where an object has a lot of attributes

Second: extension operators

const obj1 = {
  name: "zs".age: 13};const obj2 = {
  name: "ls".sex: "Female"};constnewObj = { ... obj1, ... obj2 };console.log(newObj === obj1); //false
console.log(newObj === obj2); //false
Copy the code

It is possible to merge objects quickly by extending the operator’s properties, with the disadvantage of requiring a new variable to be accepted

Object.assign() (most recommended)

const obj1 = {
  name: "zs".age: 13};const obj2 = {
  name: "ls".sex: "Female"};const newObj = Object.assign(obj1, obj2);
console.log(newObj === obj1); //true
console.log(newObj === obj2); //false
console.log(newObj);
/ / {
// name:'ls',
// age:13,
/ / sex: 'woman'
// }
Copy the code

The object.assign () method takes a target Object and one or more source objects as arguments. If the Object has the same attribute, the attribute of the later Object overwrites the attribute of the previous Object.

The principle is that subsequent objects are added to the target object through the set access property, so the value returned is actually the first target object. You can add access properties to the target object to see the overwriting process

const obj1 = {
  set a(val) {
    console.log(val); }};Object.assign(obj1, { a: "tom" }, { a: "jerry" }, { a: "dog" });
//'tom'
//'jerry'
//'dog'
Copy the code

This method can be used in a number of scenarios, which are particularly useful, for example:

  1. Some students may assign empty values to the data in the form one by one to clear the form. In fact, the efficiency is very low. However, if you use object.assign () and $options, the efficiency is very high
/ / everyday
this.ruleForm.name=' ';
this.ruleForm.phone=' ';
this.ruleForm.imgUrl=' ';
this.ruleForm.des=' '; . Ten thousand words are omitted here// Use object. assign and $options
Object.assign(this.ruleForm,this.$options.data().ruleForm)

Copy the code

$options stores the initial value of the Vue instance, so object.assign () overrides the value to quickly reset the form. Similarly, ruleForms can be quickly assigned when the form data is being modified

const { data } = await xxxApi.getList();
Object.assign(this.ruleForm, data);
Copy the code