Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda