0

I have the following array in my React naitve app.

  const [items, setItems] = useState([
    { answers: [{ id: 1 }, { id: 2 }] },
    { answers: [{ id: 1 }] },
    { answers: [{ id: 1 },] },
  ]);

I want to delete item from first row with id 2 So the final should look like that

[
    { answers: [{ id: 1 }] },
    { answers: [{ id: 1 }] },
    { answers: [{ id: 1 }] },
  ]

How can i do that ? I tried to start like this

  const onDelete = useCallback((itemId) => {
    var newItems = [...items];

    newItems = newItems[0].answers.filter(....) //I don't know how to continue

    setItems(newItems);
  }, []);

Sorry for the question but I'm new to react-native and javascript!

4 Answers 4

2

Assuming that you want to change the first object and you want do dynamically filter the answers based on your itemId, the onDelete function would look like this:

  const onDelete = useCallback((itemId) => {
    setItems((prev) => [
      { answers: prev[0].answers.filter(({ id }) => id !== itemId) },
      ...prev.slice(1),
    ]);
  }, []);
Sign up to request clarification or add additional context in comments.

Comments

1

I've expanded @rjumatov answer to allow removing answer ids at any index.

const onDelete = useCallback((answerId=2,itemIndex=0)=>{
  const newItems = [...items];
  let currentItem = newItems[itemIndex]
  currentItem.answers = currentItem.answers.filter(({id})=> id !== answerId)
  newItems[itemIndex] = currentItem;
  setItems(newItems);
},[]);

Comments

0

You should create a new object, whose answers property is the filtered original. The filter callback can be ({id}) => id != 2:

   newItems[0] = { answers: newItems[0].answers.filter(({id}) => id != 2) };

Comments

0
newItems = newItems.map(item => { return item.answers.filter(answer => answer.id !== 2)})

1 Comment

I dont think this would work as it delete all answer keys of the id 2 and alter items to be nothing a list of ids

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.