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

230
Vistas
How to delete array element from JSON array of objects by ID

This is probably quite easy, but giving me trouble. Given this JSON structure:

 "playlists" : [
      {
        "id" : "1",
        "owner_id" : "2",
        "song_ids" : [
          "8",
          "32"
        ]
      },
      {
        "id" : "2",
        "owner_id" : "3",
        "song_ids" : [
          "6",
          "8",
          "11"
        ]
      },
      {
        "id" : "3",
        "owner_id" : "7",
        "song_ids" : [
          "7",
          "12",
          "13",
          "16",
          "2"
        ]
      }
    ]

How would you delete an object from the array by key/value? In this case by ID? playlist.splice(1,1)? playlist.delete(id)? Not sure how to do this elegantly. Let's say I wish to delete the element with ID = 3, how to get this result:

 "playlists" : [
      {
        "id" : "1",
        "owner_id" : "2",
        "song_ids" : [
          "8",
          "32"
        ]
      },
      {
        "id" : "2",
        "owner_id" : "3",
        "song_ids" : [
          "6",
          "8",
          "11"
        ]
      }
]


about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Using Array.filter, you can filter out elements that don't match a certain condition. For example:

const result = playlists.filter(playlist => playlist.id !== '2');

Here's a working demo:

/* Example Data */
const playlists = [
  {
    "id" : "1",
    "owner_id" : "2",
    "song_ids" : [ "8", "32"]
  },
  {
    "id" : "2",
    "owner_id" : "3",
    "song_ids" : ["6", "8","11" ]
  }
];

/* Takes a list of playlists, and an ID to remove */
const removePlaylistById = (plists, id) =>
  plists.filter(playlist => playlist.id !== id);

/* Removes playlist ID 2 from list, prints result */
const result = removePlaylistById(playlists, '2');
console.log(result);


Another option, would be to use Array.findIndex to get the index of an element with given ID, then use Array.splice to remove that element. This will modify the array, without the need for a copy.

For example:

const indexToRemove = playlists.findIndex((pl) => pl.id === '2');
playlists.splice(indexToRemove, 1);
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