0

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?

willem
  • 42
  • 5
  • 2
    Possible duplicate of [How do I remove a particular element from an array in JavaScript?](https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript) – Alexander Staroselsky Nov 07 '18 at 17:34

1 Answers1

2

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.

findIndex doc ref