文章 评论 浏览 27
const isObj = (a) => typeof a === 'object' && a !== null; const simpleObj = (obj) => { const stack = [obj]; let current; const out = {}; const _p = Symbol('_p'); const _pNode = Symbol('_pNode'); while(stack.length) { current = stack.pop(); if (isObj(current)) { Object.keys(current).reverse().forEach(key => { stack.push(current[key]); if (!isObj(current[key])) { let temp = key; let currentTemp = current; while(currentTemp && currentTemp[_p]) { temp = `${currentTemp[_p]}.${temp}`; currentTemp = currentTemp[_pNode]; } out[temp] = current[key]; } else { current[key][_pNode] = current; current[key][_p] = key; } }); } } return out; } var entry = { a: { b: { c: { dd: 'abcdd' } }, d: { xx: 'adxx' }, e: 'ae' } } console.log(simpleObj(entry));
文章 0 评论 0
接受
第 111 题:编程题,写个程序把 entry 转换成如下对象