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

145
Visualizações
Get all items from a list using javascript filter method

I want to filter items from the list. When a certain category will be provided as a value to the target variable, the filter method should return only items with that category. but when no category is provided I want to get items of all categories regardless of category. In my code below works ok, but I want more clear logic to filter items when no category is provided as a target.

let items = [
  {'name':"A",'category':"a"},
  {'name':"B",'category':"b"},
  {'name':"C",'category':"c"}
]
let target;
console.log(items.filter( item => {
    if(target==undefined){
    return true;
  }
    return (item['category']===target);
}));
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can create a function that takes a list of items and an optional target. In case a target was passed return the filtered list, otherwise, return the list itself:

const filterByCategoryIfTargetProvided = (arr = [], target) =>
  target ? arr.filter(({ category }) => category === target) : arr;

const items = [ {'name':"A",'category':"a"}, {'name':"B",'category':"b"}, {'name':"C",'category':"c"} ];

console.log( filterByCategoryIfTargetProvided(items) );
console.log( filterByCategoryIfTargetProvided(items, 'a') );

about 4 years ago · Juan Pablo Isaza Relatório

0

This function requires an array and the object you want to filter. You can use it to filter the object based on the category, name or any other object key. Thanks.

let items = [
{ name: "A", category: "a" },
{ name: "B", category: "b" },
{ name: "C", category: "c" },
];

const filterItems = (arr, itemToFilter) => {
if (itemToFilter) {
    const keyToFilter = Object.keys(itemToFilter);
    const filteredItem = arr.filter((eachItem) => {
        return eachItem[keyToFilter] === itemToFilter[keyToFilter];
    });
    return filteredItem;
} else {
    return arr;
}
};

console.log(filterItems(items, { category: "a" }));

about 4 years ago · Juan Pablo Isaza Relatório

0

You coiuld filter by either no category or with the category.

const
    filter = (data, category) => data.filter(o => !category || o.category === category),
    items = [{ name: "A", category: "a" }, { name: "B", category: "b" }, { name: "C", category: "c" }];

console.log(filter(items));
console.log(filter(items, 'a'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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