wankdanker / node-object-mapper

Copy properties from one object to another.
MIT License
276 stars 73 forks source link

Empty object being created when mapping an empty array of objects #72

Open ge022 opened 4 years ago

ge022 commented 4 years ago

Mapping an empty array (ex. empty result from db) to a mapping profile with a sub profile like this:

const mappingProfile = { 
"[].Id": "[].Id",
"[].file": {
    key: "[].file",
    transform: (value) => objectMapper(value, fileMappingProfile),
 }
}

returns [ {} ] Adding "?" to the file does not fix this. As a workaround, I am checking the source length to decide whether or not to map.

Another issue I ran into is that a nulls do not work on a sub mapping if the source is null. For example, mapping this object which has a null "file" key, does not include the key in the result:

"[].contents[].file": {
  key: "[].contents[].file",
  transform: (value) => objectMapper(value, fileMappingProfile),
},

result:

[
  {
      "Id": 3,
      "content": [
          {
              "Id": 2,
          }
      ]
  }
]

I've tried "?" and default, resulting in the same issue:

"[].contents[].file": {
  key: "[].contents[].file?",
  transform: (value) => objectMapper(value, null, fileModel),
  default: null
},
wankdanker commented 4 years ago

Has this worked for you in a previous version of object-mapper?

arnaudjnn commented 4 years ago

Same issue. Did you find a workaround? I get empty objects.

sylvainlegault commented 4 years ago

It work when there is no transform function, adding the transform function always create a dest = {} object, which is the one that end up being added to the array. My expectation is that transform should not be called if there is no value, default should be call in that case.

GauravChinavle commented 2 years ago
{ 
           "sourceObject": {
                "key": "destObject",
                transform: function (value,source,dest) {
                    if(Array.isArray(source.rootKey) && source.rootKey.length == 0) {
                        return [];
                    } else {
                        return [...dest.destObject];
                    }
                },
                default: []
            }
 }

It worked for me. but make sure you put it at the end of the key mapping In response i was getting and { response: { data: { resultingArray: [] } } } and what object mapper was doing { response: { data: { resultingArray: [ {} ] } } }