javaScript数组互转对象
1、数组转对象
1.1、需求
[{ id: 1, name: '张三' },{ id: 2, name: '李四' }]
转换为
1.2、forEach
let arr = [{ id: 1, name: '张三' },{ id: 2, name: '李四' }]
let obj = {}
arr.forEach(item => obj[item.value] = item.name)
console.dir(obj)
/*
Object
1: "张三"
2: "李四"
*/
1.3、reduce
let arr = [{ id: 1, name: '张三' },{ id: 2, name: '李四' }]
let obj = arr.reduce((obj, item) => ({...obj,[item.id]: item.name}), {})
console.dir(obj)
/*
Object
1: "张三"
2: "李四"
*/
2、对象转数组
2.1、需求
{1:'张三', 2:'李四'}
转换为
[{ id: 1, name: '张三' },{ id: 2, name: '李四' }]
2.2、for...in
let obj = {1:'张三', 2:'李四'}
let arr = []
for (let index in obj) {
arr.push({
'id': index,
'name': obj[index]
})
}
console.dir(arr)
/*
Array(2)
0: {id: '1', name: '张三'}
1: {id: '2', name: '李四'}
length: 2
*/
2.3、map
let obj = {1:'张三', 2:'李四'}
let arr = Object.keys(obj).map(index => ({ id: index, name: obj[index]}))
console.dir(arr)
/*
Array(2)
0: {id: '1', name: '张三'}
1: {id: '2', name: '李四'}
length: 2
*/