JavaScript - 使用while扁平化对象

135 阅读1分钟

输入

    {
                a: {
                    b: 1,
                    c: 2,
                    d: { e: 5 },
                },
                b: [1, 3, { a: 2, b: 3 }],
                c: 3,
     }

输出

        {
               'a.b': 1,
               'a.c': 2,
               'a.d.e': 5,
               'b[0]': 1,
               'b[1]': 3,
               'b[2].a': 2,
               'b[2].b': 3'c': 3
         }

code

  function flatten(obj) {
                const _map = {}; // 最终出口
                // 初始化每个单项
                function initObj(_key, _obj) {
                    return {
                        type: Array.isArray(_obj) ? "array" : "object",
                        keyStr: _key,
                        keys: Object.keys(_obj),
                        values: Object.values(_obj),
                    };
                }
                // 计算keyStr
                function initStr(_type, _keyStr, _key) {
                    // 最外层为空,所以直接返回下级key
                    if (!_keyStr) {
                        return _key
                    }
                    // 非最外层需要拼接
                    switch (_type) {
                        case "array":
                           return `${_keyStr}[${_key}]`
                        case "object":
                           return `${_keyStr}.${_key}`
                    }
                    return ''
                }
                // 可循环链表
                const current_list = [initObj("", obj)];
                let bl = !!current_list.length;
                while (bl) {
                    const { values, keys, keyStr, type } = current_list.shift();
                    values.forEach((nowValue, index) => {
                        const key = keys[index];
                        const strKey =  initStr(type,keyStr,key)
                        if (nowValue instanceof Object) {
                            current_list.push(initObj(strKey, nowValue));
                        } else {
                            _map[strKey] = nowValue
                        }
                    });
                    bl = !!current_list.length;
                }
                console.log(_map);
            }