Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
Removing an object from array based on properties value

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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}
              &nbsp;
              <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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda