I am using the MongoDb with the mongoose libraray. My schema is in English, but I am receiving a the same structure with German (or another) keywords.
MongoDB-Schema:
{
"Uid": Number,
"User": {
"Firstname": String,
"Lastname": String
}
}
JSON Object:
"Uid": Number,
"Benutzer": {
"Vorname": String,
"Nachname": String
}
I am receiving the JSON Object as a string and I am working with JSON.parse, the realObject is more complex, I wouldn't like to copy field by field. In case the keywords are the same, I can use a simple assignment:
const my_object = JSON.parse(file_as_string)
MyObject.findOneAndUpdate(
{ UID: my_object.Uid},
{
User: my_object.Benutzer
})
My question is: How do I convert the JSON (with the german keywords) into the schema with the english keywords?
CodePudding user response:
You probably would need to deepclone your object and translate the property names in the process.
let translations = {
"Benutzer": "User",
"Vorname": "Firstname",
"Nachname": "Lastname",
"Strasze": "Street",
"PLZ": "ZIP",
"Ort": "City",
"Nummer": "Number"
}
function deepClone(data) {
//For arrays deepclone every element in the array
if (Array.isArray(data)) {
return data.map(d => deepClone(d));
}
//For object deepclone every property and translate the property's name
//Fallback on the original name, if no translation is found
if (typeof data === "object") {
let result = {}
for (let key in data) {
result[translations[key]||key] = deepClone(data[key]);
}
return result;
}
//return primitive datatypes (number, string, bool) as they are
return data;
}
let g = {
Uid: 1, //this one is not gonna be translated because there is no translation entry
Benutzer: {
Vorname: "Papa",
Nachname: "Schlumpf",
Adressen: [ //this one is not gonna be translated because there is no translation entry
{ Strasze: "Hauptstraße", Nummer: 1, PLZ: "1234", Ort: "Schlumpfhausen" },
{ Strasze: "Hauptplatz", Nummer: 17, PLZ: "1235", Ort: "Gargamelsdorf" }
]
}
};
console.log(deepClone(g));