6 ways to traverse an object: 1. The "for...in" statement can loop through the object's own and inherited enumerable properties; 2. keys() traverses the property names, values () Traverse the property values; 3. getOwnPropertyNames(), which can return an array containing all properties, etc.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
6 ways to traverse object properties in ES6
1, for...in
Loop through the object's own and inherited enumerable properties (excluding symbol attributes)
for (let k in obj) {}
Loop through the object's own and inherited enumerable properties (loop through the object's own and inherited enumerable properties (excluding Symbol properties)
let obj = {'0':'a','1':'b','2':'c'} for (let k in obj) { console.log(k+':'+obj[k]) } //0:a //1:b //2:c
##2, Object.keys(obj)|| Object.values(obj )
Returns an array, including all enumerable properties of the object itself (excluding inheritance) (excluding Symbol properties)keys() is the pair of property names The traversal, values() is the traversal of attribute valueslet obj = {'0':'a','1':'b','2':'c'} console.log(Object.keys(obj)) //["0","1","2"] console.log(Object.values(obj)) //["a","b","c"]
##3, Object.getOwnPropertyNames(obj) Returns an array containing all the properties of the object itself (excluding properties, but including non-enumerable properties)
let obj = {'0':'a','1':'b','2':'c'}; Object.getOwnPropertyNames(obj).forEach(function(key){ console.log(key,obj[key]); }); // 0 a // 1 b // 2 c
Returns an array containing all the Symbol properties of the object itself
Example: Get the object's own Symbol value propertyvar obj = {}; var a = Symbol("a"); var b = Symbol.for("b"); obj[a] = "localSymbol"; obj[b] = "globalSymbol"; var objectSymbols = Object.getOwnPropertySymbols(obj); console.log(objectSymbols.length); // 2 console.log(objectSymbols) // [Symbol(a), Symbol(b)] console.log(objectSymbols[0]) // Symbol(a)
Returns an array containing all the properties of the object itself, regardless of the property name It is a Symbol or a string, regardless of whether it is enumerable.
const object1 = { property1: 42, property2: 13 }; const array1 = []; console.log(Reflect.ownKeys(object1)); // expected output: Array ["property1", "property2"] console.log(Reflect.ownKeys(array1)); // expected output: Array ["length"]
##6. Reflect.enumerate(obj)
Returns an Iterator object, traversing all the enumerable properties of the object itself and inherited (excluding Symbol properties), the same as the for ... in loop. 、 The above is the detailed content of What are the methods for traversing objects in es6. For more information, please follow other related articles on the PHP Chinese website!var obj = { x: 1, y: 2 };
for (var name of Reflect.enumerate(obj)) {
console.log(name);
}
// logs "x" and "y"