js数组对象的转换
Posted origin_master
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js数组对象的转换相关的知识,希望对你有一定的参考价值。
数组转对象
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]; arr.reduce((accu, cur, index) => (accu[index] = cur, accu), {}); // 或者 arr.reduce((accu, cur, index) => ({ ...accu, [index]: cur }), {}); // 或者 arr.reduce((accu, cur, index) => Object.assign(accu, { [index]: cur }), {}); console.log(obj); //{ 0: 1, 1: 2, 2: 3, 3: 4, 4: 5 }
Object.assign
const arr = [1,2,3,4,5]; Object.assign({}, arr); //{ 0: 1, 1: 2, 2: 3, 3: 4, 4: 5 } // 或者 Object.assign({}, ...arr.map((item, index) => ({ [index]: item }))); //{ 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]
reduce
const obj = { John: 111, Mary: 222 }; Object.entries(obj).reduce((accu, [name, value]) => [...accu, { name, value }], []); // [{name: \'John\', value: 111}, {name: \'Mary\', value: 222}];
reduce大法好啊, 哈哈
以上是关于js数组对象的转换的主要内容,如果未能解决你的问题,请参考以下文章