Reputation: 42
I'm working on an application where I can add groups to a user. You can choose a group from a list and that group will show above of it. (See this photo)
I want now that you only can see the groups in the dropdown where you don't belong to.
constructor(props) {
super(props)
this.state = {
groups: [],
selectedGroups: [],
group: '',
isLoading: true,
show: false
};
//bind
this.getGroups = this.getGroups.bind(this);
this.addGroup = this.addGroup.bind(this);
}
//this function will be executed when clicking on button
addGroup(e) {
e.preventDefault();
this.setState({
selectedGroups: [...this.state.selectedGroups, this.state.group], //hier worden de groepen van die gebruiker in geplaatst
groups: [] //hier moet iets gebeuren dat this.state.group wordt verwijdert uit de lijst
})}
My propery groups look like this:
[{"id":1,"company_id":1,"name":"Support","created_at":null,"updated_at":null},
{"id":2,"company_id":1,"name":"Administrator","created_at":null,"updated_at":null},
{"id":3,"company_id":1,"name":"Redacteur","created_at":null,"updated_at":null}]
My property, group, is the selected group when clicking on the button.
Example: if I select Administrator and click on the button, the property group will have "Administrator" as value. Administrator will then be add to the Array selectedGroups. Now I want that the object with the name "Administrator" removes from the groups array.
The property groups have to look like this then:
{"id":2,"company_id":1,"name":"Administrator","created_at":null,"updated_at":null},
{"id":3,"company_id":1,"name":"Redacteur","created_at":null,"updated_at":null}]
How can I delete a object from an Array of objects?
Upvotes: 0
Views: 67
Reputation: 116
To my mind, in your case you need to find an index of the element in the array which you wanna delete by using method below:
const index = array.findIndex(value => value.id === id);
and then delete this index:
const result = array.splice(index, 1);
Where array
it is your array where you wanna delete the object, id
this an ID of an object which should be deleted. You can also check if a findIndex
has founded something before doing splice
and if nothing founded findIndex
will return -1
.
Upvotes: 2