0

call an api function with any passed as body, need to convert to type but with conditions

the type using is

export type aircraft = {
   _id?: ObjectId,
   groupid: ObjectId,
   reg: string,
   type?: string,
   desc?: string,
   arc?: Date,
 }

is there a better way of doing this????

export function addAircraft(newAircraft: any) {

  const insertAircraft: aircraft = {
    reg: newAircraft.reg,
    groupid: new ObjectId(newAircraft.groupid),
    type: newAircraft.type,
    desc: newAircraft.desc,
    arc: new Date(newAircraft.arc)
  }
}

I do not want any fields that are missing from newAircraft to be in insertAircraft

I have looked at object.entries but a little lost as i am looking at the input object not the target object

tried the above result _id is generated so that is fine

example:

 newAircraft = {
    reg: G-ABCD,
    groupid: '',
    desc: 'Test Description',
 }

RESULT

 insertAircraft = {
    reg: G-ABCD,
    groupid: '',
    type: null,
    desc: 'Test Description',
    arc : null
 }

so in above field arc and type is null, i would don't want it there at all.

i.e.

insertAircraft = {
    reg: G-ABCD,
    groupid: '',
    desc: 'Test Description'
 }

also if there is a date type, needs to convert to date as per the function

Liam
  • 27,717
  • 28
  • 128
  • 190
  • 1
    Does this answer your question? [typescript - cloning object](https://stackoverflow.com/questions/28150967/typescript-cloning-object) – Liam Jan 12 '23 at 17:01
  • Make `newAirplane` a [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype). And pull the defined keys from it. – Jared Smith Jan 12 '23 at 17:18

1 Answers1

0

So i've now got the right results, probably not the best coding

export function convertToAircraft(aircraft: any) {

let retval = new Map()

const dateType = [ 'arc', 'annual']
const objectType = [ '_id', 'groupid']

for (const [k, v] of (Object.entries(aircraft) as unknown as [string, any][])) {
    let newval: any

    if (dateType.includes(k)) { newval = new Date(v); }
    else
        if (objectType.includes(k)) { newval = new ObjectId(v); }
        else
            {
                newval = v
            }
    
    retval.set(k,newval)
    
}
const newAircraft: aircraft = Object.fromEntries(retval)

return newAircraft
} 

but gives me the result i need, i can now add to the types and it will convert the type to ObjectId or Date