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

163
Visualizações
How to filter an array of objects based on ID?

I have the following array of objects, I want to loop through it and filter based on the id or code that I pass into the function.

state.products = [{id = 1, name = Bottle},{id = 2, name = umbrella}, {id = 3, name = shoe}]

const getVal = (id)=> {

 const av = state.products.filter((s) s.productId == id)

}

The following doesn't seem to iterate through the array and check through each object? I am getting an empty array for console.log(av)

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You are on a right way, but you are not using Array.filter properly.

And also the provided array of object is not also in a good format. Object should be in a key:value pairs.

state.products = [
    { id: 1, name: "Bottle" },
    { id: 2, name: "umbrella" },
    { id: 3, name: "shoe" }
]

const getAllArrayExcept = (id) => {
    // this will return all the array except provided id
    return state.products.filter((s) => s.id !== id)
}

const getOnlyArray = (id) => {
    // this will return only item which match the provided id
    return state.products.filter((s) => s.id === id)
}

console.log(getAllArrayExcept(1))
/*
output: [{ id = 2, name = umbrella }, { id = 3, name = shoe }]
*/
console.log(getOnlyArray(1))
/*
output: [{ id = 1, name = Bottle }]
*/

Here is the working snippet:

const products = [
    { id: 1, name: "Bottle" },
    { id: 2, name: "umbrella" },
    { id: 3, name: "shoe" }
]

const getAllArrayExcept = (id) => {
    // this will return all the array except provided id
    return products.filter((s) => s.id !== id)
}

const getOnlyArray = (id) => {
    // this will return only item which match the provided id
    return products.filter((s) => s.id === id)
}

console.log("All array except: ", getAllArrayExcept(1))
console.log("Only provided item in array: ", getOnlyArray(1))

about 4 years ago · Santiago Trujillo 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