0

I have an array of an object with multiples arrays inside. I'm trying to remove the item when I click the button, but it's returning undefined

Data Json

[
  {
    "services": [
      {
        "id": "1b975589-7111-46a4-b433-d0e3c0d7c08c",
        "name": "PIX"
      },
      {
        "id": "91d4637e-a17f-4b31-8675-c041fe06e2ad",
        "name": "Income"
      }
    ],
    "accountTypes": [
      {
        "id": "1f34205b-2e5a-430e-982c-5673cbdb3a68",
        "name": "Digital Account"
      }
    ],
    "channels": [
      {
        "id": "875f8350-073e-4a20-be20-38482a86892b",
        "name": "Chat"
      }
    ]
  }
]

HandleDeleteItem

const handleDeleteFilter = (itemId: string) => {
    const items = filters.flatMap((param) => {
      Object.entries(param).flatMap(([key, arr]) =>
        arr.filter(({ id }) => id !== itemId)
      )
    })
    setFilters(items)
  }

Function Button onClick

onClick={() => handleDeleteFilter(filter.id)}
1
  • what is filter.id in the call of the function Commented Jul 20, 2021 at 21:24

1 Answer 1

1

Your first flatMap arrow function uses brackets (=> { ... }) but doesn't have a return statement. Try this instead:

const handleDeleteFilter = (itemId: string) => {
    const items = filters.flatMap((param) => {
        // Added a return here
        return Object.entries(param).flatMap(([key, arr]) =>
            arr.filter(({ id }) => id !== itemId)
        )
    })
    setFilters(items)
}

It isn't very clear what filters is (I assume your shown JSON), so I haven't checked whether your function is logically correct.

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

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.