zoukankan      html  css  js  c++  java
  • JavaScript 对象扁平化

        <script>
            const obj = {
                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  
                }
            */
    
            function flatObj(o) {
                if (typeof o !== 'object') throw new Error(`TypeError: need a object type but get a ${typeof o}`)
    
                const res = {}
                const flat = (obj, preKey = '') => {
                    Object.entries(obj).forEach(([key, value]) => {
                        /* 
                            handle key
                            preKey默认是''
                            如果是递归入口 preKey有值 需要加 . 或者 [] 分割
                        */
                        let newKey = key
                        if (preKey) {
                            newKey = `${preKey}${Array.isArray(obj) ? `[${newKey}]` : `.${newKey}`}`
                        }
    
                        /* 
                            handle value
                            引用类型继续递归拍平
                            基本类型设置到结果对象上
                        */
                        if (value && typeof value === 'object') {
                            return flat(value, newKey)
                        }
                        res[newKey] = key
                    })
                }
    
                flat(o)
                return res
            }
            console.log(flatObj(obj))
        </script>
      
    
  • 相关阅读:
    C++ reference
    C++ const 限定符
    POJ 1222 EXTENDED LIGHTS OUT(高斯消元)
    poj 2185
    poj 2406
    poj 2752
    hdu 6171
    hdu 6127
    uva 3708
    hdu 6092
  • 原文地址:https://www.cnblogs.com/ltfxy/p/15638172.html
Copyright © 2011-2022 走看看