2017-02-10 56 views
0

如果我有2 JSON對象,如:映射2 JSON對象中的NodeJS

const conversionMap = { 
    name : "First Name" 
}; 

const userObject = { 
    name : "MTae" 
} 

那麼我將要在mapped2Json(conversionMap, userObject, mappedResult)爲了有mappedResult === { First Name : "MTae" }

回答

1

這裏做是遞歸函數,它將映射嵌套對象以及

https://jsbin.com/cukuxuxopi/edit?js,console

function mapped2Json(map, data) { 
    var result = { } 
    for (var key in map) { 
    var value = map[key] 

    if (typeof value === 'object') { 
     result[key] = mapped2Json(value, data[key]) 
    } else { 
     result[value] = data[key] 
    } 
    } 

    return result 
} 


const map = { 
    name: 'First Name', 
    surname: 'Last name', 
    birthday: { 
    day: 'Day', 
    month: 'Month', 
    year: 'Year', 
    } 
} 

const data = { 
    name: 'Michael', 
    surname: 'Gordan', 
    birthday: { 
    day: 13, 
    month: 2, 
    year: 1990, 
    } 
} 

console.log(mapped2Json(map, data)) 
+0

它的工作完美xD,tks這麼多! –