1.数组转对象
1)展开运算符...
const arr = [1,2,3,4,5]
const obj = {...arr}
console.log(obj) // {1,2,3,4,5}
2).Object.assign()
方法用于将所有可枚举属性的值从一个或多个源对象分配到目标对象。它将返回目标对象。
const arr = ["one","two","three"]
const obj = Object.assign({},arr)
console.log(obj) //Object { 0: "one", 1: "two", 2: "three" }
3).forEach 遍历获得每项的对象
const arr = ['one','two','three'];
let obj = {}
arr.forEach((item,index) =>{obj[index] = item})
console.log(obj) //Object { 0: "one", 1: "two", 2: "three" }
2.对象转换为数组
1).Object.keys(obj)
const obj = {a:1,b:2,c:3}
const arr = Object.keys(obj).map(item =>{return obj[item]})
console.log(arr) //Array [1, 2, 3]
2).Object.values(obj)
参数:obj 被返回可枚举属性值的对象
返回值:一个包含对象本身所有枚举属性值的数组
描述: Object.values()返回是一个数组,其元素在对象上找到的可枚举属性值.属性的顺序与通过 手动循环对象的属性值所给出的顺序相同
var obj = {a:1,b:2,c:3}
var arr = Object.values(obj)
console.log(arr) //Array [1, 2, 3]
3).Array.from() 类似数组对象转换为真数组(必须有length长度才能转换)
const obj = {
0:"name",
1:"age",
2:"sex",
length:3}
const res = Array.from (obj)
console.log(res) //Array ["name", "age", "sex"]