Here is my situation, i am importing from multiple data sources into my json backend.
The mapping file will look something like this sample below. So the question is how could i go about it to effectively look up the mapping on an import from this json file and use it when to import the data into my backend. So the concept is to pass 2 objects to my function, the mapping file and the json object which holds the data from the vendor. Then i have to use the mapping and loop thru data to create an object / doc and insert in my backend with correct mappings.
{
"vendor" : "ABCVendor",
"version" : "2.01",
"mappings" : [
{ "fieldName" : "fName",
"dbName" : "FirstName",
"required" : true,
"type" : "string"
},
{ "fieldName" : "mName",
"dbName" : "MiddleName",
"required" : false,
"type" : "string"
},
{ "fieldName" : "lName",
"dbName" : "LastName",
"required" : true,
"type" : "string"
}
]
}
Here is what the input would look like
{
"fname" : "Steve",
"mname" : "T",
"lname" : "Miller"
}
Ad here is what i would like to get out
{
"FirstName" : "Steve",
"MiddleName" : "T",
"LastName" : "Miller"
}
You could do something like this, if the insert is always the same.
this may not be the most performant way to do it though.
"use strict";
const fileConfig = {
"vendor": "ABCVendor",
"version": "2.01",
"mappings": [
{
"fieldName": "fName",
"dbName": "FirstName",
"required": true,
"type": "string"
},
{
"fieldName": "mName",
"dbName": "MiddleName",
"required": false,
"type": "string"
},
{
"fieldName": "lName",
"dbName": "LastName",
"required": true,
"type": "string"
}
]
};
const funcInput = {
"fName": "Steve",
"mName": "T",
"lName": "Miller"
};
function change(config, input) {
const result = {};
config.mappings.forEach((fe) => {
result[fe.dbName] = input[fe.fieldName];
});
return result;
}
console.log(change(fileConfig, funcInput))
You can do this all with reduce (although there does appear to be a casing difference in your mapping vs your object which ive used toLowerCase to get aeround - maybe uunncessary if that was just a typo on your part)
const config = {
"vendor" : "ABCVendor",
"version" : "2.01",
"mappings" : [
{ "fieldName" : "fName",
"dbName" : "FirstName",
"required" : true,
"type" : "string"
},
{ "fieldName" : "mName",
"dbName" : "MiddleName",
"required" : false,
"type" : "string"
},
{ "fieldName" : "lName",
"dbName" : "LastName",
"required" : true,
"type" : "string"
}
]
}
const input = {
"fname" : "Steve",
"mname" : "T",
"lname" : "Miller"
}
const result = config.mappings.reduce(
(acc, {fieldName, dbName}) => ({...acc, [dbName]: input[fieldName.toLowerCase()]})
,{})
console.log(result)