Five ways to traverse objects in javascript Example code

Five ways to traverse objects in javascript Example code

Prepare

Let's prepare a test object obj first.

Code Listing 1

var notEnum = Symbol("inherited non-enumerable symbol");
var proto = {
    [Symbol("Inherited enumerable symbol")]: "Inherited enumerable symbol",
    name: "Inherited enumerable properties"
};
// Non-enumerable properties Object.defineProperty(proto, "age", {
    value: "Inherit non-enumerable properties"
});
// Non-enumerable symbol property Object.defineProperty(proto, notEnum, {
    value: "Inherit non-enumerable symbol"
});

var obj = {
    job1: "Own enumerable attribute 1",
    job2: "Own enumerable attribute 2",
    [Symbol("own enumerable symbol")]: "own enumerable symbol"
};
// Inherit Object.setPrototypeOf(obj, proto);
// Non-enumerable properties Object.defineProperty(obj, "address", {
    value: "Own non-enumerable attributes"
});
// Non-enumerable symbol attribute var ownNotEnum = Symbol("Own non-enumerable symbol");
Object.defineProperty(obj, ownNotEnum, {
    value: "Own non-enumerable symbol"
});

Five weapons

for…in

This is a veteran in the field of object traversal. In this way, you can traverse all enumerable properties of the object itself and its inheritance (excluding Symbol types).

Code Listing 2

for(var attr in obj){
    console.log(attr,"==",obj[attr]);
}
/*
job1 == own enumerable property 1
job2 == own enumerable property 2
name == inherited enumerable properties */

Object.keys

Gets an array of all enumerable properties of the object itself (excluding Symbol type)

Code Listing 3

Object.keys(obj).map((attr)=>{
    console.log(attr,"==",obj[attr]);
});
/*
job1 == own enumerable property 1
job2 == own enumerable property 2
*/

Object.getOwnPropertyNames

Gets an array of all non-Symbol property names (including non-enumerable) of the object itself

Code Listing 4

Object.getOwnPropertyNames(obj).map((attr)=>{
    console.log(attr,"==",obj[attr]);
});
/*
job1 == own enumerable property 1
job2 == own enumerable property 2
address == own non-enumerable attribute*/

Object.getOwnPropertySymbols

Gets an array of all the attribute names (including non-enumerable) of the object itself that are of type Symbol

Code Listing 5

Object.getOwnPropertySymbols(obj).map((attr)=>{
    console.log(attr,"==",obj[attr]);
});
/*
Symbol(own enumerable symbol) == own enumerable symbol
Symbol(own non-enumerable symbol) == own non-enumerable symbol
*/

Reflect.ownKeys

Get an array of all the property names of an object (including non-enumerable and Symbol types)

Listing 6

Reflect.ownKeys(obj).map((attr)=>{
    console.log(attr,"==",obj[attr]);
});
/*
job1 == own enumerable property 1
job2 == own enumerable property 2
address == Own non-enumerable attribute Symbol (own enumerable symbol) '==' 'Own enumerable symbol'
Symbol (own non-enumerable symbol) '==' 'own non-enumerable symbol'
*/

Summarize

Instructions for the arsenal, choose the appropriate weapon according to your needs.

API operate Own attributes Non-enumerable properties Inherited properties Symbol Properties
for…in Traversal yes no yes no
Object.keys Returns an array of attributes yes no no no
Object.getOwnPropertyNames Returns an array of non-Symbol attributes yes yes no no
Object.getOwnPropertySymbols Returns the Symbol attribute array yes yes no yes
Reflect.ownKeys Returns an array of attributes yes yes no yes

The most powerful of the five weapons is Reflect.ownKeys, which works on both Symbol and non-enumerable types. It is simply the combination of Object.getOwnPropertyNames and Object.getOwnPropertySymbols.

Extensions

Object.values

Gets an array of values ​​of all enumerable properties (excluding Symbol types) of the object itself

Listing 7

Object.values(obj).map((val)=>{
    console.log(val);
});
/*
Own enumerable properties 1
Own enumerable properties 2
*/

Object.entries

Gets an array of key-value pairs of all enumerable properties (excluding Symbol types) of the object itself

Listing 7

Object.entries(obj).map((val)=>{
    console.log(val);
});
/*
[ 'job1', 'Own enumerable attribute 1' ]
[ 'job2', 'Own enumerable attribute 2' ]
*/

hasOwnProperty

Checks whether an object's own properties contain the specified property and returns a boolean

Quoted from MDN: JavaScript does not protect the hasOwnProperty property name, so it is possible that an object has a property with this property name, so directly use the hasOwnProperty method on the prototype chain

Code Listing 8

for(var attr in obj){
    if (Object.prototype.hasOwnProperty.call(obj,attr)){
        console.log("Own attributes: :",attr);
    }else{
        console.log("Inherited attributes: :",attr);
    }
}
/*
Own properties:: job1
Own properties:: job2
Inherited properties:: name
*/

propertyIsEnumerable

Checks whether a property is enumerable in the specified object and returns a boolean

Code Listing 9

Reflect.ownKeys(obj).map((attr) => {
    if (Object.prototype.propertyIsEnumerable.call(obj, attr)) {
        console.log("Enumerable properties: :", attr);
    } else {
        console.log("Non-enumerable attributes: :", attr);
    }
});
/*
Enumerable properties:: job1
Enumerable properties:: job2
Non-enumerable property:: address
Enumerable property:: Symbol (own enumerable symbol)
Non-enumerable property:: Symbol (own non-enumerable symbol)
*/

refer to

MDN Object

Summarize

This concludes this article about five ways to traverse objects in JavaScript. For more relevant content about traversing objects in JavaScript, 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:
  • Methods for traversing object properties and values ​​in js
  • Javascript array and dictionary usage and object attribute traversal skills
  • JS 5 ways to traverse objects
  • js code to traverse the properties of an object
  • Summary of how to easily traverse object properties in JS
  • The difference between traversing arrays and objects in JS and the detailed explanation of how to recursively traverse objects, arrays, and properties
  • js simple traversal to obtain the attribute value in the object method example
  • JS recursive traversal object to obtain Value value method skills
  • Traversing the properties and values ​​of objects in js

<<:  MySQL method of generating random numbers, strings, dates, verification codes and UUIDs

>>:  Docker builds kubectl image implementation steps

Recommend

HTML drawing user registration page

This article shares the specific implementation c...

Example code for implementing an Upload component using Vue3

Table of contents General upload component develo...

Docker Stack deployment method steps for web cluster

Docker is becoming more and more mature and its f...

What is em? Introduction and conversion method of em and px

What is em? em refers to the font height, and the ...

A brief discussion on Nginx10m+ high concurrency kernel optimization

What is high concurrency? The default Linux kerne...

JavaScript implements a box that follows the mouse movement

This article shares the specific code of JavaScri...

Mysql optimization techniques for querying dates based on time

For example, to query yesterday's newly regis...

How to convert JavaScript array into tree structure

1. Demand The backend provides such data for the ...

Vue implements infinite loading waterfall flow

This article example shares the specific code of ...

In-depth explanation of MySQL user account management and permission management

Preface The MySQL permission table is loaded into...

25 Examples of News-Style Website Design

bmi Voyager Pitchfork Ulster Grocer Chow True/Sla...

Use Vue3 to implement a component that can be called with js

Table of contents Preface 1. Conventional Vue com...