冷血

文章 评论 浏览 27

冷血 2022-05-04 13:55:21
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));

第 111 题:编程题,写个程序把 entry 转换成如下对象

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文