1、数组转换成对象
const arr = [
{ label: '男', value: 0 },
{ label: '女', value: 1 }
]
function f(arr) {
const obj = {}
for (let i = 0; i < arr.length; i++) {
obj[arr[i].value] = arr[i].label
}
return obj
}
const obj = f(arr)
console.log(obj) // obj ===> {0: '男', 1:'女'}
2、对象转换成数组
const obj = { 0: '男', 1: '女' }
function f(obj) {
let arr = []
for (let key in obj) {
// console.log(key, typeof key)
arr.push({ label: obj[key], value: +key })
}
return arr
}
const arr = f(obj)
console.log(arr) // arr ===> [{label: '男', value: 0},{label: '女', value: 1}]
3、数组(每一个数据都是一个对象)转换成树形结构数据
let data = [
{ id: '01', name: '张大大', pid: '', job: '项目经理' },
{ id: '02', name: '小亮', pid: '01', job: '产品leader' },
{ id: '03', name: '小美', pid: '01', job: 'UIleader' },
{ id: '04', name: '老马', pid: '01', job: '技术leader' },
{ id: '05', name: '老王', pid: '01', job: '测试leader' },
{ id: '06', name: '老李', pid: '01', job: '运维leader' },
{ id: '07', name: '小丽', pid: '02', job: '产品经理' },
{ id: '08', name: '大光', pid: '02', job: '产品经理' },
{ id: '09', name: '小高', pid: '03', job: 'UI设计师' },
{ id: '10', name: '小刘', pid: '04', job: '前端工程师' },
{ id: '11', name: '小华', pid: '04', job: '后端工程师' },
{ id: '12', name: '小李', pid: '04', job: '后端工程师' },
{ id: '13', name: '小赵', pid: '05', job: '测试工程师' },
{ id: '14', name: '小强', pid: '05', job: '测试工程师' },
{ id: '15', name: '小涛', pid: '06', job: '运维工程师' }
]
function toTree(data) {
let result = []
if (!Array.isArray(data)) {
return result
}
let map = {}
data.forEach(item => {
map[item.id] = item
})
data.forEach(item => {
let parent = map[item.pid]
if (parent) {
(parent.children || (parent.children = [])).push(item)
} else {
result.push(item)
}
})
return result
}
console.log(toTree(data))