Daniel Logvin
Daniel Logvin

Reputation: 502

React-Native remove object from Array

I'm trying to remove an object from the array, even though, I'm not sure how to grab the object, which basically makes the code that is written not make anything.

Let me show the existing array:

Object {
    "created_at": "2020-06-30T11:22:53.000000Z",
    "icon": "subjectImgs/509-1080x1080.jpg",
    "id": 2,
    "name": "Test",
    "updated_at": "2020-06-30T11:22:53.000000Z",
    "user_id": 1,
  },
  Object {
    "created_at": "2020-06-04T18:32:25.000000Z",
    "icon": "subjectImgs/698-1080x1080.jpg",
    "id": 1,
    "name": "history",
    "updated_at": "2020-06-04T18:32:25.000000Z",
    "user_id": 1,
  }, 
  Object {
    "created_at": "2020-07-08T16:32:03.000000Z",
    "icon": "subjectImgs/698-1080x1080.jpg",
    "id": 21, // Here is the ID
    "name": "123",
    "updated_at": "2020-07-08T16:32:03.000000Z",
    "user_id": 1,
  },
}

When the event is listened to, I get the array of the object that was just deleted:

Object {
  "socket": null,
  "subject": Object {
    "created_at": "2020-07-08T16:32:03.000000Z",
    "icon": "subjectImgs/698-1080x1080.jpg",
    "id": 21, // Here is the ID
    "name": "123",
    "updated_at": "2020-07-08T16:32:03.000000Z",
    "user_id": 1,
  },
}

Now, the way I'm trying to delete it is the following:

            .listen('SubjectRemoved', ev => {
                var array = this.state.subjects
                this.setState({ subjects: array.filter((id) => id != ev.subject.id) })
            });

but apparently, this is not working. I assume because of using id really gets nothing.

Upvotes: 1

Views: 70

Answers (1)

Nacho Zullo
Nacho Zullo

Reputation: 571

I think that the problem is in the filter method:

array.filter((id) => id != ev.subject.id) // here id is an elemt of the array not the real id

You could try

array.filter((subject) => subject.id != ev.subject.id) //if is an array of subjects 

or

array.filter((elem) => elem.subject.id != ev.subject.id) //if is an array of objects like {socket: null, subject: {... with the fields }}

If you think that the ev.subject.id is not working you could just console.log it before the filter senetence.

Upvotes: 2

Related Questions