Home > Back-end >  Function to map an object throws "Expected an assignment or function call and instead saw an ex
Function to map an object throws "Expected an assignment or function call and instead saw an ex

Time:09-30

I have this function below on typescript and I cannot compile due to the follwing "Expected an assignment or function call and instead saw an expression". Even searching on SO I don't really understand why yet. Any help is appreciated :)

const function = (list: IListType | undefined) =>{
   let listpush: AType[]=[]
    list?.item.map(
        it =>
        {(it.values && it.values?.key && it.values?.value)?
            listpush.push({
                attr1: it.name,
                attr2: it.values.key,
                attr3: it.values.value,
            }):null
        }
    )
}

CodePudding user response:

You are using a new javascript feature called Optional chaining which is only supported since typescript 3.7. Make sure you have at least version 3.7 or newer in your react project.

Keep in mind that map is meant to transform an array, you have to return a value for each item in the callback. I changed it to forEach in the example below:

const myFunction = (list: IListType | undefined) =>{
    let listpush: AType[]=[];

    list?.item.forEach(it => {
        if(it.values && it.values?.key && it.values?.value){
            listpush.push({
                attr1: it.name,
                attr2: it.values.key,
                attr3: it.values.value,
            })
        }
    })

    return listpush;
}

and alternative would be to use filter and map:

const myFunction = (list: IListType | undefined): AType[] => {
    if(!list){
        return [];
    }

    return list.item.filter(it => {
        return it.values && it.values?.key && it.values?.value;
    }).map(item => ({
        attr1: it.name,
        attr2: it.values.key,
        attr3: it.values.value,
    }))
}

CodePudding user response:

Mistake 1: no return value

Mistake 2: 'function' is a keyword and cannot be used as an identifier

Misconception: use Array.map() instead of forEach and a buffer variable

Misconception: make the function parameter nullable instead of expecting "undefined" (which does the same)

Refactoring advice: use filter to remove elements you dont want to map

const mapperFunction = (list?: IListType): AType[] =>
    list?.item.filter(it => it.values && it.values?.key && it.values.value)
              .map(it => ({ attr1: it.name, attr2: it.values.key, attr3: it.values.value }))
  • Related