JS 实现合并对象为JSON格式,属性名中的"."号转换为嵌套的对象属性

156 阅读1分钟

例如:

     输入: const data1 = {"a.b.c": 1, "a.b.d": 2}
           const data2 = {"a.b.e": 3, "a.b.f": 4, "a.g.h": 5}
           mergeObj2Json(data1, data2)
     输出: { "a": { "b": { "c": 1, "d": 2, "e": 3, "f": 4 } } 

实现:

function mergeObj2Json(o1, o2){
    const mergeObj = {...o1, ...o2}
    const mergeKeys = Object.keys(mergeObj)
    const obj = {}
    mergeKeys.forEach((key) => {
        const props = key.split('.')
        props.forEach((cur, index) => {
            const isLastIndex = props.length - 1 == index
            const value = isLastIndex ? mergeObj[key] : {}
            if (index == 0 && !obj[cur]){
                obj[cur] = value
            }
            if (index != 0 ){
               const parentObj = props.slice(0, index).reduce((prev,cur)=>{
                return prev[cur]
               },obj)
               if (!parentObj[cur]) parentObj[cur] = value
            }
        })
    })
    return obj
}