How to Use Object Method in JavaScript

Original text: How To Use Object Methods in JavaScript
Author: Tania Rascia
Translator: Boxuan

introduce

In JavaScript, object Is a collection of key/value pairs. Values can contain attributes and methods, and can contain all other JavaScript data types, such as strings, numbers, and Boolean values.

All objects in JavaScript come from the parent Object Constructor. Object provides us with many practical built-in methods and can be used directly in a single object. Differ Prototype Method of Array For example, sort() and reverse() can only be used by array instances. Object methods come directly from Object constructors and use object instances as parameters. This is called a static method.

This tutorial will introduce important built-in object methods, each of which covers specific methods and provides examples of how to use them.

premise

To make full use of this tutorial, you should be familiar with creating, modifying, and using objects, which you can use in "Understanding Objects in JavaScript" Look at these objects in one article.

For additional guidance on JavaScript, you can view "How to Code JavaScript" Series.

Object.create()

Object.create() Method is used to create a new object and link it to an existing object prototype.

We can create a job object instance and extend it to more specific objects.

// Initialize an object with properties and methods
const job = {
    position: 'cashier',
    type: 'hourly',
    isAvailable: true,
    showDetails() {
        const accepting = this.isAvailable ? 'is accepting applications' : "is not currently accepting applications";

        console.log(`The ${this.position} position is ${this.type} and ${accepting}.`);
    }
};

// Use Object.create to pass properties
const barista = Object.create(job);

barista.position = "barista";
barista.showDetails();
Output

The barista position is hourly and is accepting applications.

The barista object now has a position attribute - but all other attributes and methods can be obtained through the prototype of job. Minimizing duplication through Object.create() for code retention DRY Very effective.

Object.keys()

Object.keys() An array containing object keys is created.

We can create an object and print an array of keys.

// Initialize an object
const employees = {
    boss: 'Michael',
    secretary: 'Pam',
    sales: 'Jim',
    accountant: 'Oscar'
};

// Get the keys of the object
const keys = Object.keys(employees);

console.log(keys);
Output

["boss", "secretary", "sales", "accountant"]

Object.keys() can also be used to iterate over the keys and values of an object.

// Iterate through the keys
Object.keys(employees).forEach(key => {
    let value = employees[key];

     console.log(`${key}: ${value}`);
});
Output

boss: Michael
secretary: Pam
sales: Jim
accountant: Oscar

There is a difference between the enumerable properties returned by the for-in loop and Object.keys():
for-in loops also traverse prototype properties
Object.keys() returns only its own (instance) properties

Object.keys() is also useful for checking the length of objects.

// Get the length of the keys
const length = Object.keys(employees).length;

console.log(length);
Output

4

Using this length attribute, we can calculate that employees contain four own attributes.

Object.values()

Object.values() Create an array containing object values.

// Initialize an object
const session = {
    id: 1,
    time: `26-July-2018`,
    device: 'mobile',
    browser: 'Chrome'
};

// Get all values of the object
const values = Object.values(session);

console.log(values);
Output

[1, "26-July-2018", "mobile", "Chrome"]

Object.keys() and Object.values() allow you to return data from objects.

Object.entries()

Object.entries() Create nested arrays of key/value pairs of objects.

// Initialize an object
const operatingSystem = {
    name: 'Ubuntu',
    version: 18.04,
    license: 'Open Source'
};

// Get the object key/value pairs
const entries = Object.entries(operatingSystem);

console.log(entries);
Output

[
    ["name", "Ubuntu"]
    ["version", 18.04]
    ["license", "Open Source"]
]

Once we have a key / value pair array, we can use the forEach() method to loop and process the results.

// Loop through the results
entries.forEach(entry => {
    const [key, value] = entry;

    console.log(`${key}: ${value}`);
});
Output

name: Ubuntu
version: 18.04
license: Open Source

The Object.entries() method returns only the attributes of the object instance itself, not any attributes that can be inherited through its prototype.

Object.assign()

Object.assign() Used to copy the value of one object to another object.

We can create two objects and merge them using the Object.assign() method.

// Initialize an object
const name = {
    firstName: 'Philip',
    lastName: 'Fry'
};

// Initialize another object
const details = {
    job: 'Delivery Boy',
    employer: 'Planet Express'
};

// Merge the objects
const character = Object.assign(name, details);

console.log(character);
Output

{firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}

It can also be used Spread syntax To accomplish the same task. In the following code, we will declare the character object by expanding the syntax to merge the name and details objects.

// Initialize an object
const name = {
    firstName: 'Philip',
    lastName: 'Fry'
};

// Initialize another object
const details = {
    job: 'Delivery Boy',
    employer: 'Planet Express'
};

// Merge the object with the spread operator
const character = {...name, ...details}

console.log(character);
Output

{firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}

Spread syntax It also becomes shallow-cloning in object grammar.

Object.freeze()

Object.freeze() Prevent modifying attributes and values of objects, and prevent adding or deleting attributes in objects.

// Initialize an object
const user = {
    username: 'AzureDiamond',
    password: 'hunter2'
};

// Freeze the object
const newUser = Object.freeze(user);

newUser.password = '*******';
newUser.active = true;

console.log(newUser);
Output

{username: "AzureDiamond", password: "hunter2"}

In the example above, we tried to overwrite hunter2 with ***** by rewriting the password, but the password value could remain unchanged. We also tried to add a new attribute, active, but did not.

Object.isFrozen() can be used to determine whether an object has been frozen and return a Boolean value.

Object.seal()

Object.seal() Prevent adding new attributes to objects, but allow modification of existing attributes. This method is similar to Object.freeze(). Refresh the console to avoid errors before implementing the following code.

// Initialize an object
const user = {
    username: 'AzureDiamond',
    password: 'hunter2'
};

// Seal the object
const newUser = Object.seal(user);

newUser.password = '*******';
newUser.active = true;

console.log(newUser);
Output

{username: "AzureDiamond", password: "*******"}

The new active attribute was not added to the sealed object, but the password attribute was successfully changed.

Object.isSealed() can be used to determine whether the object is closed and return a Boolean value.

Object.getPrototypeOf()

Object.getPrototypeOf() It is used to obtain the internal hiding of [[Prototype]] objects, and can also be accessed through the _proto_ attribute.

In this example, we can create an array that can access the Array prototype.

const employees = ['Ron', 'April', 'Andy', 'Leslie'];

Object.getPrototypeOf(employees);
Output

[constructor: ƒ, concat: ƒ, find: ƒ, findIndex: ƒ, pop: ƒ, ...]

We can see in this prototype output that employees array accesses pop, find, and other array prototype methods. We can prove this by testing the employees prototype.

Object.getPrototypeOf(employees) === Array.prototype;
Output

true

This method can be used to obtain more information about an object or to ensure that it can access the prototype of another object.

There is another correlation. Object.setPrototypeOf() Method adds a prototype to another object. It is recommended that you use Object.create() because it is faster and has higher performance.

conclusion

Objects have many useful ways to help us modify, protect, and iterate over them. In this tutorial, we review how to create and distribute new objects, iterate over their keys and/or values, and freeze or seal objects.

If you need to view JavaScript objects, you can read "Understanding Objects in JavaScript" . If you want to familiarize yourself with the prototype chain, you can check it out "Understanding prototypes and inheritance in JavaScript".

Keywords: Javascript Attribute Ubuntu Session

Added by chewydence on Sun, 19 May 2019 15:48:24 +0300