递归对象转数组

新手上路,请多包涵

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))
阅读 3.8k
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":[]}]}]}]

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏