node-object-mapper icon indicating copy to clipboard operation
node-object-mapper copied to clipboard

Empty object being created when mapping an empty array of objects

Open ge022 opened this issue 6 years ago • 4 comments

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
},

ge022 avatar Dec 12 '19 16:12 ge022

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

wankdanker avatar Dec 27 '19 19:12 wankdanker

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

arnaudjnn avatar May 15 '20 03:05 arnaudjnn

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.

sylvainlegault avatar Sep 12 '20 19:09 sylvainlegault

{ 
           "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: [ {} ] } } }

GauravChinavle avatar Jul 07 '22 08:07 GauravChinavle