List of properties and methods of objects. JavaScript exampl... open

List of properties and methods of objects. JavaScript example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

Using the for(string) loop, we can iterate over the object as a regular array and get all its properties and methods:

    const person = {
        name: "Alexander",
        age: 33,
        print() {
            console.log(`Name: ${this.name}  Age: ${this.age}`);
        }
    };

    for (const prop in person) {
        console.log(prop, " : ", person[prop]);
    }

in console:

name  :  Alexander
age  :  33
print  :  function() {
            console.log(`Name: ${this.name}  Age: ${this.age}`);
        }

Object.entries()

The Object.entries() function takes an object as a parameter and returns an array of “property_name – value” pairs, where each property-value pair represents an array:

    const person = {
        name: "Alexander",
        age: 33,
        print() {
            console.log(`Name: ${this.name}  Age: ${this.age}`);
        }
    };

    for (const prop of Object.entries(person)) {
        console.log(prop);
    }

in console:

    ["name", "Alexander"]
    ["age", 33]
    ["print", ƒ]

Object.keys()

The Object.keys() function allows you to get an array of the names of all the properties of an object.

    const person = {
        name: "Alexander",
        age: 33,
        print() {
            console.log(`Name: ${this.name}  Age: ${this.age}`);
        }
    };

    console.log(Object.keys(person)); // ["name", "age", "print"]

You can iterate over this set and get the property values:

    for (const prop of Object.keys(person)) {
        const value = person[prop];    //get property value by name
        console.log(prop, value);
    }

Iterating an array using forEach

You can use forEach:

    var person = {
        name: 'Max',
        age: 28,
        job: 'Frontend'
    }

    //let's output our properties to the console
    for (var key in person) {
        if (person.hasOwnProperty(key))
            console.log(person[key])
    }

    Object.keys(person).forEach(function (key) {
        console.log(person[key])
    })

Object.values() function

The Object.values() function returns an array that contains all the property values of the object:

    const person = {
        name: "Alexander",
        age: 33,
        print() {
            console.log(`Name: ${this.name}  Age: ${this.age}`);
        }
    };
    console.log(Object.values(person)); // ["Alexander", 33, print()]
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation