对象与数组的互相转换
一、数组转对象
let arr = [
{
key: 'name',
value: '张三'
},
{
key: 'age',
value: '18'
},
]
const object = {}
arr.forEach(item => {
object[item.key] = item.value
})
console.log(object)
/**
* {
* age: '18',
* name: '张三'
* }
*/
console.log(JSON.stringify(object))
/**
* {"name":"张三","age":"18"}
*/
结果
二、数组转对象
方案一
const arr = []
const object = {
name: '张三',
age: 18
}
for (const key in object) {
arr.push({
name: key,
value: object[key]
})
}
console.log('arr', arr)
结果
方案二
const arr = []
const object = {
name: '张三',
age: 18
}
for (const key in object) {
arr.push(
{ [key]: object[key] }
)
}
console.log('arr', arr)
结果
方案三
const arr = []
const arr2 = []
const object = {
name: '张三',
age: 18
}
for (const key in object) {
arr.push(key)
arr2.push(object[key])
}
console.log('arr', arr)
console.log('arr2', arr2)
结果
方案四
const obj = {
name: '张三',
age: 18
}
const arr = Object.keys(obj)
const arr2 = Object.values(obj)
console.log('arr', arr)
console.log('arr2', arr2)
结果