Case analysis of object to array in JS

以一次实际开发中的实例,将几种对象转数组的方法都试了一遍:
      // const errorList = Object.keys(error)
      // console.log('error', error)
      // console.log('Array.from', Array.from(error))
      // console.log('keys',Object.keys(error))
      // console.log('values',Object.values(error))
      // console.log('entries',Object.entries(error))

Insert picture description here

This is the original object type structure:

Insert picture description here

1.Array.from() method

用于数组的浅拷贝。就是将一个类数组对象或者可遍历对象转换成一个真正的数组。
所满足的数组限制是: 
  1. There must be a length attribute in the object, and the length of the returned array depends on the length of length
  2. The .key value must be a numeric value,
    so the output here is an empty array
    Insert picture description here

2.Object.values(object)(ES8): a iterator that returns key values

tips:与第一种不同的是不需要length属性,返回一个对象所有可枚举属性值

Insert picture description here

3.Object.keys(object): Iterator that returns the key name

tips:返回一个对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用 for…in 循环遍历该对象时返回的顺序一致

Insert picture description here

4.Object.entries(object)(ES8): Iterator that returns key-value pairs

tips:返回一个给定对象自身可枚举属性的键值对数组

Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45416217/article/details/109250834