0

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

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

Couldn't you do this:

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

2 Comments

May be acceptable though labelOverride: undefined is not strictly the same as the absence of labelOverride.
Yes, you're right. It depends on what the OP wants but I believe it fulfills 99% of the needs and is way more understandable/short than anything else.
0

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',
    };
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.