简体   繁体   中英

Remove an object in array from array

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',
            },
          ],
        },
    ]

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

Something similar to

if(lists[0].cardItems[0].id === 1){
    lists[0].cardItems.splice(0,1);
}

Obviously this will only check that one value, but this can easily be implemented into a loop or nested loops or whatever you need. (I can't know since I can't see all of your code)

Your question is a little bit hard to understand, but this was my best guess at helping you out! If this wasn't the answer you're looking for then please give us more information so we can help you more effectively!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM