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

209
Vistas
Remove object value in array if it doesn't exist

I have an array of objects as follows

const array = [ 
{id:1,parentIds:[]}
{id:2,parentIds:[1,3]}
{id:3,parentIds:[1,2,4]}
]

How can I make it possible to remove an object's parentIds value if it doesn't exist in the array? to look something like this

const array = [ 
{id:1,parentIds:[]}
{id:2,parentIds:[1,3]}
{id:3,parentIds:[1,2]}
]
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can try this solution:

const array = [{
    id: 1,
    parentIds: []
}, {
    id: 2,
    parentIds: [1, 3]
}, {
    id: 3,
    parentIds: [1, 2, 4]
}];

const idsArr = new Set(array.map(el => el.id));

array.forEach(el => {
    el.parentIds = el.parentIds.filter(el => idsArr.has(el));
})
    
console.log(array);

about 4 years ago · Juan Pablo Isaza Denunciar

0

It's better to avoid mutating the original array parentIds, use immutation to create new array:

const array = [ 
{id:1,parentIds:[]},
{id:2,parentIds:[1,3]},
{id:3,parentIds:[1,2,4]}
]

const ids = array.map(({id}) => id)

const newArray = array.map(({parentIds,...arrayItemRest}) => {
  const newparentIds = parentIds.filter(id => ids.includes(id))
  
  return {
    ...arrayItemRest,
    parentIds: newparentIds
  }
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

const array = [ 
{id:1,parentIds:[]},
{id:2,parentIds:[1,3]},
{id:3,parentIds:[1,2,4]}
]

// Let's create an array only containing the ids
var ids = array.map(o => o.id)

// Loop array
array.forEach((object) => {
  // Loop all parent ids
  object.parentIds.forEach((id, index) => {
    // Check if we find the id in our list
    if (ids.indexOf(id) === -1) {
      // Delete item from array if not found
      object.parentIds.splice(index, 1)
    }
  })
})

// The result
console.log(array)

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