数据打平 数组转对象

**

初级数组转对象

**

const testArray = ["苹果","草莓","橘子"]
let obj = {}
for(i=0;i<testArray.length;i++){
    obj[i]=testArray[i]
}
console.log(obj)  ={0: '苹果', 1: '草莓', 2: '橘子'}

中级数组对象转对象

const testArray = [{id:1,value:"苹果"},{id:2,value:"草莓"},{id:3,value:"橘子"}]
let obj = {}
testArray.forEach(item=>{
    obj[item.id] = item.value
})
console.log(obj)  ={1: '苹果', 2: '草莓', 3: '橘子'}

高级数组对象转对象

const testArray = [
    {
     id:1,
     value:"苹果",
     children:[
         {
          id:4,
          value:"香蕉",
          children:[
              {
                  id:5,
                  value:"香蕉儿子"
              }
                  ]
         }
     ]
    },
    {
     id:2,
     value:"草莓"
    },
    {
     id:3,
     value:"橘子",
     children:[
         {
             id:7,
             value:"橘子儿子"
         }
     ]
    }
]

const arrayMap = (array)=>{
    const obj = {}

    const itemS = (config)=>{
        const {id,value,children} = config
        obj[id] = value
        if(children?.length){
            children.forEach((item)=>{
                itemS(item)
            })
        }
    }

    array.forEach(item=>{
        itemS(item)
    })

    return obj
}

console.log(arrayMap(testArray));

{1: '苹果', 2: '草莓', 3: '橘子', 4: '香蕉', 5: '香蕉儿子', 7: '橘子儿子'}


版权声明:本文为qq_43541326原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。