JavaScript object spread operator...

JavaScript object spread operator…

Object spread operator… is a syntax in JavaScript used to expand properties in an object.

Specifically, the object spread operator... is used to spread properties from one object and merge them into another object, or to create a new object.

The JavaScript spread operator was introduced in ES6. The spread operator can be used to create and clone arrays and objects, pass arrays as function parameters, remove duplicates from arrays, and more.

Usage examples

Merge objects:

const obj1 = {
    
     foo: 'foo' };
const obj2 = {
    
     bar: 'bar' };

const merged = {
    
     ...obj1, ...obj2 };
console.log(merged); // { foo: 'foo', bar: 'bar' }
在上述示例中,...obj1 和 ...obj2 将 obj1 和 obj2 对象中的属性展开,并将它们合并到一个新的对象 merged 中。

Create new object:

const obj1 = {
    
     foo: 'foo', bar: 'bar' };
const newObj = {
    
     ...obj1, baz: 'baz' };
console.log(newObj); // { foo: 'foo', bar: 'bar', baz: 'baz' }

In this example, ...obj1 expands the properties in the obj1 object and creates a new object newObj. At the same time, we can also add other attributes, such as baz: 'baz'.

Copy object:

const obj = {
    
     foo: 'foo', bar: 'bar' };
const copy = {
    
     ...obj };
console.log(copy); // { foo: 'foo', bar: 'bar' }

By using the object spread operator... we can quickly create a copy of an object and assign it to another variable.

Guess you like

Origin blog.csdn.net/inthat/article/details/135288890