wankdanker/node-object-mapper

Multi-level array values into a single array

Opened this issue · 2 comments

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]

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:

if (o !== null) {

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

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