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

MySQL log settings and viewing methods

MySQL has the following logs: Error log: -log-err...

Install MySQL 5.7 on Ubuntu 18.04

This article is compiled with reference to the My...

Writing methods that should be prohibited in native JS

Table of contents Block-level functions Directly ...

JS implements a simple brick-breaking pinball game

This article shares the specific code of JS to im...

Proxy realizes the principle of two-way binding of Vue3 data

Table of contents 1. Advantages of proxy vs. Obje...

Difference between varchar and char types in MySQL

Table of contents aforementioned VARCHAR Type VAR...

A practical record of troubleshooting a surge in Redis connections in Docker

On Saturday, the redis server on the production s...

MySQL 5.7.17 installation and configuration graphic tutorial

The blogger said : I have been writing a series o...

Vue custom table column implementation process record

Table of contents Preface Rendering setTable comp...

MySQL dual-machine hot standby implementation solution [testable]

Table of contents 1. Concept 2. Environmental Des...

Node.js sends emails based on STMP protocol and EWS protocol

Table of contents 1 Node.js method of sending ema...

Detailed explanation of Nginx configuration file

The main configuration file of Nginx is nginx.con...