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

221
Visualizações
Dynamically change the key in a filter query

I've created a simple filtering code that filters out 0s and nulls. Perhaps not the most elegant, but it works:

var data = [{"location": 30, "year": 2019},
            {"location": 60, "year" : 1928},
            {"location": 0, "year": 2019},
            {"location": 50, "year": 0}];
    
var filteredData = [];

for (var i = 0; i < data.length; ++i) {
  if (data[i].location !== null && data[i].location != 0) {
    filteredData.push({
      location: data[i].location,
      year: data[i].year
    })
  }
};
console.log(filteredData);

Now I would like to filter out 0s and nulls for other keys (e.g. year), how can I dynamically change key?

My (perhaps naive) thinking was to create a variable indicating the key I want to filter out

Unfortunately that didn't work. Does anyone have a suggestion or help me in the right direction?

var var1 = 'year';
    
var data = [{"location": 30, "year": 2019},
            {"location": 60, "year" : 1928},
            {"location": 0, "year": 2019},
            {"location": 50, "year": 0}];

var filteredData = [];

for (var i = 0; i < data.length; ++i) {
  if (data[i].var1 !== null && data[i].var1 != 0) {
    filteredData.push({
      location: data[i].location,
      year: data[i].year
    })
  }
};

console.log(filteredData)

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Your issue is that you need to use bracket notation instead of dot notation for variable keys.

That said, JavaScript has an Array filter method

You can then use every to have dynamic keys in an array:

const data = [{"location": 30, "year": 2019},
            {"location": 60, "year" : 1928},
            {"location": 0, "year": 2019},
            {"location": 50, "year": 0}];

const notZero = ["location","year"]

const filteredData = data.filter(item => notZero.every(key => item[key] !== 0))

console.log(filteredData)

about 4 years ago · Juan Pablo Isaza Relatório

0

instead of data[i].var1 try data[i][var1]. the square brackets allows you to have a dynamic key.

about 4 years ago · Juan Pablo Isaza Relatório

0

If you can have 0 or null in your data, you need to do this:

const data = [{"location": 30, "year": 2019},
            {"location": 60, "year" : 1928},
            {"location": 0, "year": 2019},
            {"location": 50, "year": 0}];

const filteredData = data.filter(item => !Object.values(item).filter(value => !value).length)

This lets you dynamically check all values within an object and check if all of them are truthy values, thereby catching all falsy values.

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