I want to remove an object from my List array based on its properties value. Right now I am using findIndex to see if there is an index ID matching my event.target.id.
This is an example of one of the objects in my list array:
{artist: "artist name",
genre: "RnB",
id: 1,
rating: 0,
title: "song name"}
This is my code:
console.log(e.target.id);
const list = this.state.playlist;
list.splice(
list.findIndex(function(i) {
return i.id === e.target.id;
}),
1
);
console.log(list);
}
how ever, instead of it removing the clicked item from the array, it removes the last item, always.
When I do this:
const foundIndex = list.findIndex((i) => i.id === e.target.id)
console.log(foundIndex)
I get -1 back.
What's the problem here?
Use filter for this. Use it to filter out the objects from state where the id of the button doesn't match the id of the current object you're iterating over. filter will create a new array you can then update your state with rather than mutating the existing state (which is bad) which is what is currently happening.
Assuming you're using React here's a working example.
const { Component } = React;
class Example extends Component {
constructor() {
super();
this.state = {
playlist: [
{id: 1, artist: 'Billy Joel'},
{id: 2, artist: 'Madonna'},
{id: 3, artist: 'Miley Cyrus'},
{id: 4, artist: 'Genesis'},
{id: 5, artist: 'Jethro Tull'}
]
};
}
// Get the id from the button (which will be
// a string so coerce it to a number),
// and if it matches the object id
// don't filter it into the new array
// And then update the state with the new filtered array
removeItem = (e) => {
const { playlist } = this.state;
const { id } = e.target.dataset;
const updated = playlist.filter(obj => {
return obj.id !== Number(id);
});
this.setState({ playlist: updated });
}
render() {
const { playlist } = this.state;
return (
<div>
{playlist.map(obj => {
return (
<div>{obj.artist}
<button
data-id={obj.id}
onClick={this.removeItem}
>Remove
</button>
</div>
);
})}
</div>
);
}
};
ReactDOM.render(
<Example />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>