数组转对象
-
forEach
const arr = [1,2,3,4,5]; let obj = {}; arr.forEach((item,index) => {obj[index] = item; }) console.log(obj); //{0: 1, 1: 2, 2: 3, 3: 4, 4: 5}
-
Object.fromEntries
const arr = [1,2,3,4,5]; let obj = {}; obj = Object.fromEntries(arr.map((item,index) => [index, item])); console.log(obj); //{0: 1, 1: 2, 2: 3, 3: 4, 4: 5}
-
reduce
const arr = [1,2,3,4,5]; let obj = {}; obj = arr.reduce((accu, cur, index) => (accu[index] = cur, accu), {}); console.log(obj); //{0: 1, 1: 2, 2: 3, 3: 4, 4: 5}
-
Object.assign
const arr = [1,2,3,4,5]; let obj = {}; obj = Object.assign({}, arr); console.log(obj); //{0: 1, 1: 2, 2: 3, 3: 4, 4: 5}
-
开展运算符 …
const arr = [1,2,3,4,5]; obj = {...arr}; console.log(obj); //{0: 1, 1: 2, 2: 3, 3: 4, 4: 5}
对象转数组
-
Array.from
let obj = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, length: 5}; console.log(Array.from(obj)); // [1,2,3,4,5]
-
Object.entries
let obj = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}; console.log(Object.entries(obj).map(([,val]) => val)); // [1,2,3,4,5]