6 Ways to Elegantly Handle Objects in JavaScript

6 Ways to Elegantly Handle Objects in JavaScript

Preface

Like other programming languages, JavaScript has its own data types such as numbers, strings, arrays, objects, etc. Objects are a very important data type in JavaScript. They have many useful methods that can be used to easily handle objects in daily project development.

This article introduces 6 methods that can be used in projects. Take this opportunity to deepen your understanding of their usage.

1. Object.freeze()

Object.freeze() method prevents the data in an object from being modified, that is, it freezes an object so that properties cannot be added, updated, or deleted from the object.

const author = {
    name: "Quintion",
    city: "Shenzhen",
    age: 18,
    validation: true,
};

Object.freeze(author);

author.name = "QuintionTang";
author.province = "Guangdong";
delete author.age;
console.log(author); // { name: 'Quintion', city: 'Shenzhen', age: 18, validation: true }

As shown in the code above, the attribute name is updated, the attribute province is added, and the attribute age is deleted, but there is no change in the final object.

2. Object.seal()

Object.seal() method is somewhat similar to Object.freeze() . Prevents adding new properties to an object and removing properties, but allows changing and updating existing properties.

const author = {
    name: "Quintion",
    city: "Shenzhen",
    age: 18,
    validation: true,
};

Object.seal(author);

author.name = "QuintionTang";
author.province = "Guangdong";
delete author.age;
console.log(author); // { name: 'QuintionTang', city: 'Shenzhen', age: 18, validation: true }

As you can see from the above code, adding new attributes and deleting attributes are invalid, only updating the attribute name is effective.

3. Object.keys()

Object.keys() method returns an array containing the names of all the keys of the parameter object. The order of the attribute names in the array is consistent with the order returned when traversing the object normally.

Take a look at the following code:

const author = {
    name: "Quintion",
    city: "Shenzhen",
    age: 18,
    validation: true,
};

console.log(Object.keys(author)); // [ 'name', 'city', 'age', 'validation' ]

You can see that the result printed in the above code is an array containing the keys as output. The output results can be processed or iterated using array methods.

console.log(Object.keys(author).length); // 4

4. Object.values()

Object.values() is similar to Object.keys() , but Object.values() gets the values ​​of all attributes in the object and returns an array of values.

const author = {
    name: "Quintion",
    city: "Shenzhen",
    age: 18,
    validation: true,
};

console.log(Object.values(author)); // [ 'Quintion', 'Shenzhen', 18, true ]

5. Object.create()

Object.create() creates a new object based on the prototype __proto__ of an existing object. Let's look at the following code:

const author = {
    firstName: "Quintion",
    lastName: "Tang",
    fullName() {
        return `${this.firstName} ${this.lastName}`;
    },
};

const newAuthor = Object.create(author);
console.log(newAuthor); // {}
newAuthor.firstName = "Ronb";
newAuthor.lastName = "Joy";
console.log(newAuthor.fullName()); // Ronb Joy

In the above code, object. create() is used to create a new object newAuthor with the prototype of author object. In this way, in the new object newAuthor you can change the corresponding attribute values ​​​​just like changing the attribute values ​​​​of author object. Doesn’t this look a bit like inheritance? Yes, class inheritance can be achieved using Object.create .

6. Object.entries()

Object.entries() allows you to get the keys and values ​​of an object, returning a multidimensional array where each dimension contains each key and value, such as [鍵, 值]

const author = {
    firstName: "Quintion",
    lastName: "Tang",
    fullName() {
        return `${this.firstName} ${this.lastName}`;
    },
};

console.log(Object.entries(author));

The output is as follows:

[
  [ 'firstName', 'Quintion' ],
  [ 'lastName', 'Tang' ],
  [ 'fullName', [Function: fullName] ]
]

Summarize

This article briefly introduces the six common methods of objects and provides corresponding sample codes. In the actual process of coding and processing objects, using the above methods can make the code more elegant.

This concludes this article about 6 ways to elegantly process objects in JavaScript. For more content related to JavaScript processing objects, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • 3 ways to create JavaScript objects
  • JavaScript Dom Object Operations
  • Five ways to traverse objects in javascript Example code

<<:  The difference and usage of single-line and double-line layout in Flex mobile layout

>>:  Solution to the problem that MySQL commands cannot be entered in Chinese

Recommend

How to modify server uuid in Mysql

Source of the problem: If the slave server is the...

Detailed tutorial on MySql installation and uninstallation

This article shares the tutorial of MySql install...

Detailed explanation of binary and varbinary data types in MySQL

Preface BINARY and VARBINARY are somewhat similar...

Records of using ssh commands on Windows 8

1. Open the virtual machine and git bash window a...

This article will show you the basics of JavaScript: deep copy and shallow copy

Table of contents Shallow copy Deep Copy Replenis...

How to introduce img images into Vue pages

When we learn HTML, the image tag <img> int...

Awk command line or script that helps you sort text files (recommended)

Awk is a powerful tool that can perform some task...

How to modify the sources.list of Ubuntu 18.04 to Alibaba or Tsinghua mirror

1. Backup source list The default source of Ubunt...

HTML unordered list bullet points using images CSS writing

Create an HTML page with an unordered list of at l...

Examples of correct judgment methods for data types in JS

Table of contents Preface Can typeof correctly de...

Using JS to implement binary tree traversal algorithm example code

Table of contents Preface 1. Binary Tree 1.1. Tra...

Implementation of pushing Docker images to Docker Hub

After the image is built successfully, it can be ...

How to resize partitions in CentOS7

Yesterday, I helped someone install a system and ...