目录
一、数组转对象
1.forEach法
let arr = [
{
key: 'sno',
value: '219980536'
},
{
key: 'name',
value: '小明'
},
{
key: 'age',
value: '20'
},
]
const object = {}
arr.forEach(item => {
object[item.key] = item.value
})
console.log(object)
2.Object.fromEntries()
Object.fromEntries()可以实现键值对数组转成了对象。
const newArray = [
['name', '小明'],
['age', '20']
]
console.log(Object.fromEntries(newArray) )
3.Map
Map
是一种叫做字典的数据结构,字典是以[键,值]的形式存储
//先将数组转成Map
const arr = ["小明","小虎","小妹"];
const arrChangeMap = (arr) => new Map(arr.map( (value,key) => [key,value]));
//再Map 转为对象
const map = arrChangeMap(arr);
const mapChangeObj = (map) => {
let obj = {};
for(let [k,v] of map) {
obj[k] = v;
}
return obj;
}
console.log(mapChangeObj(map));
4.reduce
const arr = [
['name', '小明'],
['age', '22']
]
const handleChange = (arr) => {
return Array.from(arr).reduce((prev,[key,value])=> {
return Object.assign(prev,{[key]:value})
},{})
}
console.log(handleChange(arr))
二、对象转数组
1.Object.entries()
Object.entries()
将对象转成一个自身可枚举属性的键值对数组。
const object = { name: '小明', age: '20' }
const arr = Object.entries(object)
console.log(arr)
2.push
const object = { name: '小明', age: '20' }
const arr = []
for (const key in object) {
arr.push({ [key]: object[key] })
}
console.log(arr)