Home > OS >  Mapping one JSON object to another
Mapping one JSON object to another

Time:08-10

I have a REST API that receives some JSON data. The fields in this data come from another records systems that uses different names to refer to the same things.

For this reason, I need to map the fields in the incoming object to fields in the object which I will store in our database. So for example, the incoming object might look like:

{
    "caseId": 9876    
    "userId": 123456,
}

and the outgoing object will need to be

{
    "case_id": 9876
    "user": {
        "id": 123456
    }
}

Mapping fields like caseId is easy enough. But for fields like userId where I may potentially need to map them several levels deep into nested objects, is there any library or easy technique to do such a mapping? The ideal solution would allow me to specify the mappings like so:

{
    "caseId": "case_id",
    "userId": "user.id"
{

CodePudding user response:

We can split by dot then assign to appropriate object names.

var original = {
  "caseId": 9876,
  "userId": 123456,
}

var mapping = {
  "caseId": "case_id",
  "userId": "user.id"
}


var result = {};
Object.entries(original).forEach(function([key, value]) {
  var new_name = mapping[key]

  if (new_name) {
    var arr = new_name.split(".");
    var pointer = result;
    for (var i = 0; i < arr.length - 1; i  ) {
      pointer[arr[i]] = {}
      pointer = pointer[arr[i]];
    }
    pointer[arr[arr.length - 1]] = value;
  } else {
    // default copy?
    result[key] = value;
  }
})

console.log(result)

CodePudding user response:

When it comes to mapping - I've stopped relying on libraries. It's usually a lot of setup and there's never a complete solution. It's easier to just write a method that takes one model and returns a the mapped model

  • Related