递归对象转数组

咚咚
  • 3
新手上路,请多包涵

js想做一个递归深层对象转数组,数组的title为对象的键加上父级的键一直这样迭代,但是最后有些问题,想问大佬们有解决方案嘛?

const obj={

        a:{
            yangbo:"",
            cer:''
            },
            b:{
                v:{
                    c:34
                },
                ker:{
                    wie:12
                }
            }
    }
    let pre = ''
    const jsonToArrTree = (json) => {
        let data = Object.keys(json).map( (item) =>  {
            pre += (pre ? '.':'') + item
            let ops = {
                title:pre,
                children:[]
            }
            let child = json[item]
            if(Object.prototype.toString.call(child) === '[object Object]'  && Object.keys(child).length > 0){
                ops.children = jsonToArrTree(child)
            }
            pre = ''
            return ops
        })
        pre = ''
        return data
    }
    console.log(jsonToArrTree(obj))
回复
阅读 1.4k
2 个回答

你看下这是不是你要的

const obj={
            a:{
                yangbo:"",
                cer:''
            },
            b:{
                v:{
                    c:34
                },
                ker:{
                    wie:12
                }
            }
          };
function obj2Arr(obj, keys= []){
    return Object.keys(obj).map(key=>{
        let temp_keys = [...keys];
        temp_keys.push(key);
        return {
            'title': temp_keys.join('.'),
            'children': obj2Arr(obj[key], temp_keys),
        }
    })
}
obj2Arr(obj)

clipboard.png

var func = (obj,pName) => Object.getOwnPropertyNames(obj).map(n=>{let name = pName ? ${pName}.${n} : ${n}; return {title: name, children: Object.prototype.toString.call(obj[n]) === '[object Object]' ? func(obj[n],name): []}})

func(obj)
===>
[{"title":"a","children":[{"title":"a.yangbo","children":[]},{"title":"a.cer","children":[]}]},{"title":"b","children":[{"title":"b.v","children":[{"title":"b.v.c","children":[]}]},{"title":"b.ker","children":[{"title":"b.ker.wie","children":[]}]}]}]

你知道吗?

宣传栏