Home > Web Front-end > JS Tutorial > body text

Tips for using JavaScript objects Rest and Spread (with code)

不言
Release: 2019-03-22 09:35:01
forward
2181 people have browsed it

The content of this article is about the usage skills of JavaScript objects Rest and Spread (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The Rest and Spread operators can be used for more than just resting parameters and expanding arrays.

Here are 7 little-known tips for using Rest and Spread with JavaScript objects.

Add properties

Clone an object while adding additional properties to the (shallow) cloned object.

In this example, user is cloned and the password attribute is added to userWithPass.

const user = { id: 100, name: 'Howard Moon'}
const userWithPass = { ...user, password: 'Password!' }

user //=> { id: 100, name: 'Howard Moon' }
userWithPass //=> { id: 100, name: 'Howard Moon', password: 'Password!' }
Copy after login

Object Merge

Merge two objects into a new object.

Merge Part1 and Part2 into user1.

const part1 = { id: 100, name: 'Howard Moon' }
const part2 = { id: 100, password: 'Password!' }

const user1 = { ...part1, ...part2 }
//=> { id: 100, name: 'Howard Moon', password: 'Password!' }
Copy after login

Objects can also be merged using the following syntax:

const partial = { id: 100, name: 'Howard Moon' }
const user = { ...partial, id: 100, password: 'Password!' }

user //=> { id: 100, name: 'Howard Moon', password: 'Password!' }
Copy after login

Exclude object attributes

Attributes can be removed using the destructuring rest operator. Here, password is removed and the remaining attributes are returned as rest.

const noPassword = ({ password, ...rest }) => rest
const user = {
  id: 100,
  name: 'Howard Moon',
  password: 'Password!'
}

noPassword(user) //=> { id: 100, name: 'Howard moon' }
Copy after login

Dynamic exclusion properties

The function accepts a prop as parameter. Properties can be dynamically removed from a clone using computed object property names.

const user1 = {
  id: 100,
  name: 'Howard Moon',
  password: 'Password!'
}
const removeProperty = prop => ({ [prop]: _, ...rest }) => rest
//                     ----       ------
//                          \   /
//                dynamic destructuring

const removePassword = removeProperty('password')
const removeId = removeProperty('id')

removePassword(user1) //=> { id: 100, name: 'Howard Moon' }
removeId(user1) //=> { name: 'Howard Moon', password: 'Password!' }
Copy after login

Sort properties

Sometimes properties are not in the order we need. Using some tricks, we can push properties to the top of the list, or move them to the bottom.

To move the id to the first position, add id: undefined to the front of the new Object before extending the object.

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

const organize = object => ({ id: undefined, ...object })
//                            -------------
//                          /
//  move id to the first property

organize(user3)
//=> { id: 300, password: 'Password!', name: 'Naboo' }
Copy after login

To move password to the last property, destructure password from the object. Then reset the password attribute after using the Rest operator.

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

const organize = ({ password, ...object }) =>
  ({ ...object, password })
//              --------
//             /
// move password to last property

organize(user3)
//=> { name: 'Naboo', id: 300, password: 'Password!' }
Copy after login

Default properties

Default properties are values ​​that are only set if they are not contained in the original object.

In this example, user2 does not contain the quotes attribute. The setdefaults function ensures that all objects have the quotes attribute set, otherwise it will be set to [].

When calling setDefaults (user2), the return value will contain the quotes attribute: [].

When calling setDefaults (user4), because user4 already has the quotes attribute, this attribute will not be modified.

const user2 = {
  id: 200,
  name: 'Vince Noir'
}

const user4 = {
  id: 400,
  name: 'Bollo',
  quotes: ["I've got a bad feeling about this..."]
}

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

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

setDefaults(user4)
//=> {
//=>   id: 400,
//=>   name: 'Bollo',
//=>   quotes: ["I've got a bad feeling about this..."]
//=> }
Copy after login

If you want the default value to appear first instead of last, you can also write like this:

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

Attribute renaming

By combining the above techniques, you can create a function to rename the property.

Suppose there are some object attribute names with uppercase IDs that should be lowercase IDs. First deconstruct the ID from the object and then add it back as an id when the object is Spread.

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

const user = {
  ID: 500,
  name: "Bob Fossil"
}

renamed(user) //=> { id: 500, name: 'Bob Fossil' }
Copy after login

Bonus: Adding conditional attributes

Thanks to @vinialbano for pointing out that you can also add attributes conditionally. In this example, password will only be added if password is true!

const user = { id: 100, name: 'Howard Moon' }
const password = 'Password!'
const userWithPassword = {
  ...user,
  id: 100,
  ...(password && { password })
}

userWithPassword //=> { id: 100, name: 'Howard Moon', password: 'Password!' }
Copy after login

This article has ended here. For more exciting content, you can pay attention to the JavaScript Tutorial Video column of the PHP Chinese website!

The above is the detailed content of Tips for using JavaScript objects Rest and Spread (with code). 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