-2

I want to delete the 1 ids of cardItems of my list with 0 ids and keep the order of the lists. what is the best way?

   lists: [
        {
          id: '0',
          title: 'LIST 1',
          cardItems: [
            {
              id: '0',
              text: 'Card 1',
            },
            {
              id: '1',
              text: 'Card 2',
            },
            {
              id: '2',
              text: 'Card 3',
            },
          ],
        },
    ]
2
  • 1
    Please provide the expected output. However, this looks like the kind of question that has been asked several times before. Commented Jan 17, 2021 at 10:58
  • 1
    Your description is not clear, please write your description clearly. Of course, I probably think your question is similar to this question stackoverflow.com/questions/42005096/… Commented Jan 17, 2021 at 11:11

1 Answer 1

0

You can use .find to get the list item by id, and then remove the card item using .filter:

const lists = [
  {
    id: '0',
    title: 'LIST 1',
    cardItems: [
      { id: '0', text: 'Card 1' },
      { id: '1', text: 'Card 2' },
      { id: '2', text: 'Card 3' },
    ],
  },
];

const removeCardItem = (list, listItemId, cardItemId) => {
  const arr = [...list];
  // get list item by id
  const item = arr.find(listItem => listItem.id === listItemId);
  // remove card item by id if found
  if(item)
    item.cardItems = item.cardItems.filter(cardItem =>
      cardItem.id !== cardItemId
    );
  return arr;
}

console.log( removeCardItem(lists, '0', '1') );

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.