ES6方法 数组转对象
1、利用fromEntries()和map()函数,语法“Object.fromEntries(arr.map(item => [item.key, item]))”语句;
const arr = [
{ code: "1001", city: "北京" },
{ code: "1002", city: "深圳" },
];
const obj = Object.fromEntries(arr.map(item => [item.code, item.city]));
console.log(obj);
2、利用扩展运算符“...”,语法“{...arr}”。
const arr = [
{ key: "id", name: "编号" },
{ key: "name", name: "名称" },
];
const obj = {...arr} ;
console.log(obj);
3、使用for in 遍历
for(let key in arr) { //这里key索引
obj[key] = arr[key]
}
ES6方法 对象转数组
1、Array.from
let obj2 = {
0:'zhangsan',
1:'lisi',
2:'wangwu',
length:3
}
let arr2 = Array.from(obj2)
console.log(arr2); //[ 'zhangsan', 'lisi', 'wangwu' ]
2、Array.prototype.slice.call
const arr = Array.prototype.slice.call(arrLike)