wankdanker / node-object-mapper

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

Multi-level array values into a single array #88

Open tony-oldport opened 3 years ago

tony-oldport commented 3 years ago

Apologies if there's an obvious answer to this. I think I've tried to do it every possible way except for the correct way.

If I have the following source object:

payload: {
    plans: [
        {
            planId: 1, 
            services: [
                { svcId: 100 },
                { svcId: 200 }
            ]
        },
        {
            planId: 2, 
            services: [
                { svcId: 300 }
            ]
        }
    ]
}

How can I map this to return an array of the service IDs? [100, 200, 300]

tony-oldport commented 3 years ago

This works:

const map = {
  'plans[].services': {
    key: '[]',
    transform: (sourceValue, sourceObject, destinationObject) => {
      sourceValue.forEach(val => {
        destinationObject.push(val.svcId)
      })
    }
  }
}

But only if I add && typeof o !== 'undefined' to the if statement in this line:

https://github.com/wankdanker/node-object-mapper/blob/d7a23d09aa79ab7c46c77adca14e9d7f282f7944/src/object-mapper.js#L337

Trying to dig in and understand why there is no undefined check there currently.

tony-oldport commented 3 years ago

The result without the undefined check is: [undefined, undefined, 300]