wankdanker / node-object-mapper

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

object mapper returns array with empty object when using transform function #86

Open martijnsmitt opened 3 years ago

martijnsmitt commented 3 years ago

Hi! I'm using object-mapper for simplifying objects and came across a bug(?) or at least an unexpected result. When using the transform function the mapper wil always create a empty object. Check the example below

  const data = {
    id: 123,
    body: 'Hello World',
  }
  const config = {
    'title': {
      key: 'shouldNotExist[].title',
      transform: id => id,
    },
    'body': 'message',
  }
  const result = objectMapper(data, config)
  // Results in
  // {
  //   shouldNotExist: [ {} ],
  //   message: 'Hello World'
  // }

I expected that the result wouldn't return shouldNotExist, because there is no title, but instead object-mapper returns an array with empty object. The example above is a minimal version of the real code, but isn't it possible to just return nothing and don't create an array if there is no data?

zeabdelkhalek commented 3 years ago

I have the same issue

wp55 commented 3 years ago

Has someone found a solution for this problem?

martijnsmitt commented 3 years ago

Has someone found a solution for this problem?

unfortunately not. Have you found another npm package that solved your issue? Because I'm still looking for a good object to object mapping utility

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.resultingArray];
                    }
                },
                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: [ {} ] } } }