Home > Software engineering >  Simplify JavaScript map function
Simplify JavaScript map function

Time:09-16

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
})

CodePudding user response:

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

CodePudding user response:

Couldn't you do this:

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

CodePudding user response:

I don't know if that is what you're searching for but i would optimize like that.

const newLabelItemIds = ['12345', '67890'];

const filtersToUse = filtersToChip.map((filterItem) => {
    const label = newLabelItemIds.include(filterItem.id) ? { label: 'new-label' } : {};

    return {
        ...filterItem,
        ...label,
        type: 'chip',
    };
});
  • Related