>》>》>》>》

对象转数组(嵌套拼接)

由于返回格式限制,对象不能调用数组方法

 

方法:

1、Array.from(object)

 object中必须有length属性,返回的数组长度取决于length长度
 key 值必须是数值

 

2、Object.values(object)

与第一种不同的是不需要length属性,返回一个对象所有可枚举属性值

返回数组的成员顺序:

const obj = { 100: 'a', 2: 'b', 7: 'c' }; 
Object.values(obj) 
// ["b", "c", "a"] 

 


3、Object.keys(object)

返回一个对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用 for…in 循环遍历该对象时返回的顺序一致

 

4、Object.entries(object)

返回一个给定对象自身可枚举属性的键值对数组

const obj = { foo: 'bar', baz: 42 }; 
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

 

5,使用 for…in…

function getObjectKeys(object) {
let keys = []
for(let property in object)
keys.push(property)
return keys
}
function getObjectValues(object) {
let values = []
for(let property in object)
values.push(object[property])
return values
}

 





 

 

const yearMap = resData;
            console.info(yearMap);
            this.filesTree = [];
            for (const year of Object.keys(yearMap)) {
                const yearChildren: any[] = [];
                const yearJSON = {
                    id: year,
                    label: year,
                    children: yearChildren,
                };
                // console.log('year', yearJSON);
                const monthMap = yearMap[year];
                for (const month of Object.keys(monthMap)) {
                    const monthChildren: any[] = [];
                    const monthJSON = {
                        id: month,
                        label: month,
                        children: monthChildren,
                    };
                    // console.log('month', monthJSON);
                    const fileList: any[] = monthMap[month];
                    fileList.forEach( (file) => {
                        const fileJSON = {
                            id: file.fileName,
                            label: file.fileName,
                            url: file.url,
                        };
                        // console.log('file', fileJSON);
                        monthJSON.children.push(fileJSON);
                    });
                    // console.log('2222', monthJSON );
                    yearJSON.children.push(monthJSON);
                }
                // console.log('wwww', yearJSON);
                this.filesTree.push(yearJSON);
            }
            console.log('succtt', this.filesTree)
            this.defaultExpandArr.push(this.filesTree[0].children[0].id);
        });

 

posted @ 2019-12-10 17:24  大、锤  阅读(1371)  评论(0编辑  收藏  举报