Dev
Dev

Reputation: 1746

Update state using nested map es6

My state has an array of objects that also contains an array of objects.

var state = {
  prop1: null,
  categories: [
    {
      categoryId: 1,
      tags: [
        {
          tagId: 1,
          name: 'AA11',
          status: true,
        },
        {
          tagId: 2,
          name: 'AA22',
          status: false,
        }
      ]
    },
    {
      categoryId: 2,
      tags: [
        {
          tagId: 1,
          name: 'BB11',
          status: true,
        },
        {
          tagId: 2,
          name: 'BB22', 
          status: false, // let's say i want to toggle this
        }
      ]
    },
  ]
};

I have an action that will toggle a status of a tag. This action will receive parameters categoryId and tagId.

So far I've come up with this but it doesn't work

return {
  ...state,
  categories: state.categories.map((category) => {
    category.tags.map(tag => (
      (tag.tagId === action.tagId && category.categoryId === action.categoryId) ? {
        ...tag,
        status: !tag.status,
      } : tag));
    return category;
  }),
};

Upvotes: 1

Views: 197

Answers (1)

Dev
Dev

Reputation: 1746

I finally fixed the map code.

return {
  ...state,
  categories: state.categories.map(category => ((category.id === action.categoryId) ?
    {
      ...category,
      tags: category.tags.map(tag => (tag.id === action.tagId ? {
        ...tag, status: !tag.status,
      } : tag)),
    } : category)),
};

Upvotes: 1

Related Questions