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

Detailed analysis of javascript data proxy and events

Table of contents Data Brokers and Events Review ...

How to implement CSS mask full screen center alignment

The specific code is as follows: <style> #t...

js implementation of verification code case

This article example shares the specific code of ...

A Deep Understanding of Angle Brackets in Bash (For Beginners)

Preface Bash has many important built-in commands...

Code to display the contents of a txt book on a web page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML ...

How to operate MySQL database with ORM model framework

What is ORM? ORM stands for Object Relational Map...

How to modify mysql to allow remote connections

Regarding the issue of MySQL remote connection, w...

【HTML element】Detailed explanation of tag text

1. Use basic text elements to mark up content Fir...

How to turn local variables into global variables in JavaScript

First we need to know the self-calling of the fun...

Detailed explanation of MySQL information_schema database

1. Overview The information_schema database is th...

Detailed analysis of GUID display issues in Mongodb

Find the problem I recently migrated the storage ...

Sample code for implementing image drawer effect with CSS3

As usual, let’s first post the picture effect: Th...

Implementation of nginx proxy port 80 to port 443

The nginx.conf configuration file is as follows u...