LearningRecord icon indicating copy to clipboard operation
LearningRecord copied to clipboard

已知数据格式,实现一个函数 fn 找出链条中所有的父级 id

Open Rashomon511 opened this issue 5 years ago • 0 comments

        const data = [
            {
                id: 1,
                name: '222',
                children: [{
                    id: 2,
                    name: '34',
                    children: [{
                        id: 112,
                        name: '334',
                    }, {
                        id: 112,
                        name: '354',
                    }
                    ]
                }]
            }
        ]
        const fn = (value) => {
            let graph = []
            const mapData = new Map();
            function ParentMap(data, parentId) {
                parentId = parentId || 0;
                data.forEach(item => {
                    mapData[item.id] = { ...item, parentId }
                    if (item.children) {
                        ParentMap(item.children, item.id);
                    }
                })
            }
            ParentMap(data)
            function getId(data, value) {
                graph.unshift(data[value].id)
                if (data[value].parentId !== 0) {
                    getId(data, data[value].parentId)
                }
            }
            getId(mapData, value)
            return graph;
        }

Rashomon511 avatar Jun 19 '19 01:06 Rashomon511