以一次实际开发中的实例,将几种对象转数组的方法都试了一遍:
// 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))
This is the original object type structure:
1.Array.from() method
用于数组的浅拷贝。就是将一个类数组对象或者可遍历对象转换成一个真正的数组。
所满足的数组限制是:
- There must be a length attribute in the object, and the length of the returned array depends on the length of length
- The .key value must be a numeric value,
so the output here is an empty array
2.Object.values(object)(ES8): a iterator that returns key values
tips:与第一种不同的是不需要length属性,返回一个对象所有可枚举属性值
3.Object.keys(object): Iterator that returns the key name
tips:返回一个对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用 for…in 循环遍历该对象时返回的顺序一致
4.Object.entries(object)(ES8): Iterator that returns key-value pairs
tips:返回一个给定对象自身可枚举属性的键值对数组