Ahmed
Ahmed

Reputation: 107

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 :

enter image description here

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

enter image description here

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.

Upvotes: 1

Views: 1551

Answers (3)

Diamond
Diamond

Reputation: 3428

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)
...

Upvotes: 0

Julliano Osorio
Julliano Osorio

Reputation: 305

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

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44087

Because you use Object.entries - this returns a two-dimensional array (e.g. 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)

Upvotes: 3

Related Questions