Several magical uses of JS ES6 spread operator

Several magical uses of JS ES6 spread operator

1. Add attributes

When you copy an object, you add new properties to it.

The example copies the user object to userWithPass and adds the password property.

const user = { id: 110, name: 'Kayson Li'}
const userWithPass = { ...user, password: 'Password!' }

user //=> { id: 110, name: 'Kayson Li'}
userWithPass //=> { id: 110, name: 'Kayson Li', password: 'Password!' }

2. Merge multiple objects

Multiple objects can be combined into a new object using ... Merge part1 and part2 into user1:

const part1 = { id: 110, name: 'Kayson Li' }
const part2 = { id: 110, password: 'Password!' }

const user1 = { ...part1, ...part2 }
//=> { id: 110, name: 'Kayson Li', password: 'Password!' }

3. Remove object properties

You can use destructuring in conjunction with the rest operator to remove properties from an object. In this example, password is deconstructed and other attributes are retained in the rest object and returned.

const noPassword = ({ password, ...rest }) => rest
const user = {
  id: 110,
  name: 'Kayson Li',
  password: 'Password!'
}

noPassword(user) //=> { id: 110, name: 'Kayson Li' }

4. Dynamically remove attributes

Let’s look at an example. The removeProperty function accepts a parameter prop. Using the dynamic property name feature, prop can be dynamically removed from the copied object.

const user1 = {
  id: 110,
  name: 'Kayson Li',
  password: 'Password!'
}
const removeProperty = prop => ({ [prop]: _, ...rest }) => rest
// ---- ------
// \ /
// Dynamic deconstruction const removePassword = removeProperty('password')
const removeId = removeProperty('id')

removePassword(user1) //=> { id: 110, name: 'Kayson Li' }
removeId(user1) //=> { name: 'Kayson Li', password: 'Password!' }

5. Adjust the order of attributes

Sometimes the properties of an object are not in the order we want. Using some tricks, you can move attributes to the front or back.

To move the id to the front, you can put id: undefined before the expanded object:

const user3 = {
  password: 'Password!',
  name: 'Bruce',
  id: 300
}

const organize = object => ({ id: undefined, ...object })
// -------------
// /
// Move id to the first attribute position organize(user3)
//=> { id: 300, password: 'Password!', name: 'Bruce' }

To move password to the last position, first deconstruct password from object, and then put password after the expanded object:

const user3 = {
  password: 'Password!',
  name: 'Bruce',
  id: 300
}

const organize = ({ password, ...object }) =>
  ({ ...object, password })
//--------
// /
// Move password to the end organize(user3)
//=> { name: 'Bruce', id: 300, password: 'Password!' }

6. Set property default values

When an object does not have a certain attribute, we sometimes need to add this attribute to the object and set a default value.

For example, user2 does not have a quotes attribute. The purpose of the setDefaults function is to ensure that all objects have quotes and have a default value [].

Execute setDefaults(user2) and the returned object contains quotes: [].

Execute setDefaults(user4). Since user4 already has quotes, it remains unchanged.

const user2 = {
  id: 200,
  name: 'Jack Ma'
}

const user4 = {
  id: 400,
  name: 'Lu Xun',
  quotes: ["I never said this..."]
}

const setDefaults = ({ quotes = [], ...object}) =>
  ({ ...object, quotes })

setDefaults(user2)
//=> { id: 200, name: 'Jack Ma', quotes: [] }

setDefaults(user4)
//=> {
//=> id: 400,
//=> name: 'Lu Xun',
//=> quotes: ["I never said this..."]
//=> }

If you want this attribute to be at the front, you can write it like this:

const setDefaults = ({ ...object}) => ({ quotes: [], ...object })

7: Attribute renaming

Combining the previous techniques, we can write a function to rename attributes.

Suppose some objects have uppercase ID attributes, and we want to change them to lowercase. What should we do? First, deconstruct the ID value from the object, and then merge this value into the new object and change it to a lowercase id:

const renamed = ({ ID, ...object }) => ({ id: ID, ...object })

const user = {
  ID: 500,
  name: "Zhang Quandan"
}

renamed(user) //=> { id: 500, name: '张全蛋' }

8. There are more amazing operations

You can decide whether to add a certain attribute based on conditions, which is very useful when constructing request parameters. For example, we add this attribute only if password has a value:

const user = { id: 110, name: 'Kayson Li' }
const password = 'Password!'
const userWithPassword = {
  ...user,
  id: 100,
  ...(password && { password })
}

userWithPassword //=> { id: 110, name: 'Kayson Li', password: 'Password!' }

The above are the details of several wonderful uses of JS ES6 spread operator. For more information about JS ES6 spread operator, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Understanding and application of JavaScript ES6 destructuring operator
  • JavaScript to implement the most complete code analysis of simple carousel (ES6 object-oriented)
  • JavaScript to implement the most complete code analysis of a simple shopping cart (ES6 object-oriented)
  • Detailed explanation of the differences between var, let and const in JavaScript es6
  • Differences between ES6 inheritance and ES5 inheritance in js
  • Detailed explanation of how Node.js handles ES6 modules
  • Detailed explanation of JS ES6 coding standards
  • JS quickly master ES6 class usage
  • Detailed explanation of JS ES6 variable destructuring assignment
  • About front-end JavaScript ES6 details

<<:  Detailed tutorial for installing mysql5.7.21 under Windows system

>>:  Execute initialization sql when docker mysql starts

Recommend

More popular and creative dark background web design examples

Dark background style page design is very popular...

Use of Linux ln command

1. Command Introduction The ln command is used to...

Detailed explanation of efficient MySQL paging

Preface Usually, a "paging" strategy is...

Pure CSS to achieve the effect of picture blinds display example

First, let me show you the finished effect Main i...

mysql group_concat method example to write group fields into one row

This article uses an example to describe how to u...

Ideas and methods for incremental backup of MySQL database

To perform incremental backup of the MySQL databa...

Implementation of the login page of Vue actual combat record

Table of contents 1. Preliminary preparation 1.1 ...

Use standard dl, dt, dd tags to discard table lists

Now, more and more front-end developers are starti...

Detailed explanation of root directory settings in nginx.conf

There are always some problems when configuring n...

The combination and difference between ENTRYPOINT and CMD in dockerfile

In the previous article [Detailed explanation of ...

How to deploy Spring Boot using Docker

The development of Docker technology provides a m...

Basic Implementation of AOP Programming in JavaScript

Introduction to AOP The main function of AOP (Asp...

An article teaches you how to implement a recipe system with React

Table of contents 1. Recipe Collection 1.1 Projec...