js traverse object key, value

Declare an object:

let obj = {
    
    
    name: 'Kamen',
    age: '23',
    hobby: 'eat eat eat'
  }

Method 1: Convert to operation array forEach traversal

iterate over object properties

//遍历对象属性
Object.keys(obj).forEach(key => {
    
    
    console.log(key)
  })

insert image description here
About the Object.keys() method
The Object.keys() method returns an array of a given object's self-enumerable properties. The property names in the array are arranged in the same order as they would be returned when looping through the object normally.

example

// 简单数组
const arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

// 类数组对象
const obj = {
    
     0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

// 具有随机键顺序的类数组对象
const anObj = {
    
     100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']

// getFoo 是一个不可枚举的属性
const myObj = Object.create({
    
    }, {
    
    
  getFoo: {
    
    
    value() {
    
     return this.foo; }
  }
});
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: ['foo']

Iterate over object property values

//遍历对象属性值
Object.values(obj).forEach(val => {
    
    
  console.log(val)
})

insert image description here
About the Object.values() method
The object.values() static method returns an array of the given object's own enumerable string-keyed property values.

example

const obj = {
    
     foo: "bar", baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]

// Array-like object
const arrayLikeObj1 = {
    
     0: "a", 1: "b", 2: "c" };
console.log(Object.values(arrayLikeObj1)); // ['a', 'b', 'c']

// Array-like object with random key ordering
// When using numeric keys, the values are returned in the keys' numerical order
const arrayLikeObj2 = {
    
     100: "a", 2: "b", 7: "c" };
console.log(Object.values(arrayLikeObj2)); // ['b', 'c', 'a']

// getFoo is a non-enumerable property
const myObj = Object.create(
  {
    
    },
  {
    
    
    getFoo: {
    
    
      value() {
    
    
        return this.foo;
      },
    },
  },
);
myObj.foo = "bar";
console.log(Object.values(myObj)); // ['bar']

Method 2: for/in traversal

for( let key in obj ){
    
    
    //遍历对象属性
    console.log(key)
    //遍历对象属性值
    console.log(obj[key])
  }

insert image description here
Note: This method will inherit all properties of the prototype chain, for example:

Object.prototype.pet = 'open'
for( let key in obj ){
    
    
  console.log(key)
  console.log(obj[key])
}
console.log(obj)

insert image description here
The above situation can be avoided using hasOwnProperty:

Object.prototype.pet = 'open'
  for( let key in obj ){
    
    
    if (obj.hasOwnProperty(key) === true){
    
    
      console.log(key)
      console.log(obj[key])
    }
  }
  console.log(obj)

insert image description here

Guess you like

Origin blog.csdn.net/qq_41842461/article/details/129257558