简体   繁体   中英

using .filter to delete an item from an array of objects with react/javascript

I am using .filter function of javascript to delete an element by it's ID in TypeMp3List from this array of objects. The format is like this :

在此输入图像描述

The format I want to get after doing the filter when deleting for example the MP3 with ID:33390 is this :

在此输入图像描述

This is the code I've built so far :

  showDeleteConfirmation(value, id, index, thisHandler) {
    confirm({
      title: 'Voulez vous supprimer cette audio ?',
      content: '',
      okText: 'Oui, je confirme',
      okType: 'danger',
      cancelText: 'Non',
      onOk() {
       deleteMp3Request(id);
       var { extraitMP3 } = thisHandler.state;

        var array = [];
        for (var key in extraitMP3) {
          array.push(extraitMP3[key]);
        }
        console.log('array',array)

        const result = array.map(d => ({ 
          ...d, 
          TypeMp3List: 
              Object.fromEntries(
                Object.entries(d.TypeMp3List).filter(index => index !== id)
              ) 
        }))
        console.log('result',result)


       thisHandler.setState({result: result})
       NotificationManager.success("le fichier audio est supprimé avec succès !", "");
     },
     onCancel() {
     },
    });  
  }

Problem is after mapping and filtering the console.log(result) is giving me the same results of console.log(array) . It looks like there is something wrong with the mapping and filtering and don't know exactly whats is it. any help would be appreciated.

Because you use Object.entries - this returns a two-dimensional array (eg an array containing arrays), and within your filter you're checking if each array is equal to a number. It isn't. You want to access the first element of this array - so either a little destructuring:

Object.entries(d.TypeMp3List).filter(([index]) => index !== id)

Or more verbose array notation:

Object.entries(d.TypeMp3List).filter(index => index[0] !== id)

since you want a new array based on .filter verification, try returning the result of what you are comparing:

Object.fromEntries(
    Object.entries(d.TypeMp3List).filter((index) => {
        return index !== id
    )};
)

I think you made a mistake in using filter function.

In my opinion, you can pass each item to filter function and use its id to compare with filterId .

showDeleteConfirmation(value, filterId, index, thisHandler) {
...
   Object.entries(d.TypeMp3List).filter(listItem => listItem.id !== filterId)
...

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