Search code examples
javascriptarraysecmascript-6javascript-objects

Simplify JavaScript map function


Is there a way that I can simplify this code?

I was thinking if there is a way to set { ...filterItem, type: 'chip' } as the parameter in map function instead of creating a const that will be returned in each state.

Is this type of syntax possible to do? If so, is there a specific term for it?

filtersToUse = filtersToChip.map((filterItem) => {
    const filterItem2 = { ...filterItem, type: 'chip' }

    if (filterItem.id === '12345') {
      return { ...filterItem2, labelOverride: 'new-label' }
    } else if (filterItem.id === '67890') {
      return { ...filterItem2, labelOverride: 'new-label' }
    }

    return filterItem2
})

Solution

  • Seems like you want to:

    1. Add type: 'chip' too all the elements
    2. Add labelOverride: 'new-label' if id is 12345 OR 67890

    You could do something like:

    filtersToUse = filtersToChip.map((filterItem) => ({ 
        ...filterItem, 
        type: 'chip',
        ...([ '12345', '67890'].includes(filterItem.id) ? { labelOverride: 'new-label' } : {}) 
    });
    

    Where we use object spreading to add the desired options, if needed