How to quickly assign two objects with some of the same properties in JS

Assign some properties of one object to another object

Project scenario:

Assign some field values ​​of one object to another object

obj1 = {
    
    
	"a": [ ],
	"b": "bbbb",
	"c": "cccc",
	"d":  dddd,
	"e": "eeee",
  },
obj2 = {
    
    
	"a": [ ],
	"b": "",
	"e": "",
  },

solution:

Method 1: There are many fields, and only some values ​​are taken

Object.keys(obj2 ).forEach((key) => {
    
    
          obj2 [key] = obj1 [key]
        })

Method 2: Assign all fields

obj2  = {
    
    
	...obj1
}

Method 3: Put the unnecessary attributes in front, and obj3 is the rest

const {
    
    d,...obj3} = obj1
console.log(obj3) //{"a": [ ],"b": "bbbb","c": "cccc","e": "eeee",}

Method 4: Fishing and writing

let obj3 = {
    
    
	a: obj1.a ,
	b: obj1.b,
	c: obj1.c,
	d: obj1.d,
	e: obj1.e,
}

Guess you like

Origin blog.csdn.net/wangjiecsdn/article/details/127450763
Recommended