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

265
Visualizações
Is there a way to pass keys into a JavaScript array where a a string might match multiple values of an object?

So, if I have only one key to match, then something like:

    var str = "foo";

    let [key,val] = Object.entries(obj).find(([key,val]) => val== str);
    return key;

would work beautifully. But is there a way to add multiple keys if the value matches?

To give example of an object that might match the above string:

    obj = {
      quay: "foo",
      key1: "blargh",
      yaya: "foo",
      idnet: "blat",
      blah: "foo",
      hahas: "blargh"
    }

What I want to do is return all of the "foo" keys (quay, yaya, and blah) based on the matching var str from above.

I'm sure the answer is something simple I'm overlooking.

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

0

Use filter instead of find and map to remove the values.

const obj = { quay: "foo", key1: "blargh", yaya: "foo", idnet: "blat", blah: "foo", hahas: "blargh" }

const str = 'foo';

const keys = Object.entries(obj).filter(([, val]) => val === str).map(([key]) => key);
console.log(keys);

about 4 years ago · Juan Pablo Isaza Relatório

0

Use Object.keys() to get an array of keys, and filter them with Array.filter(). In the filter's predicate function take the relevant value from the object using the key - obj[key] and compare it to str.

const str = 'foo'

const obj = {"quay":"foo","key1":"blargh","yaya":"foo","idnet":"blat","blah":"foo","hahas":"blargh"}

const keys = Object.keys(obj).filter(key => obj[key] === str)

console.log(keys)

about 4 years ago · Juan Pablo Isaza Relatório

0

You could get all the entries like you are doing, but instead of using find, filtering all the entries with the value on str that you want to find and mapping it to a list. Like this:

const str = "foo";

const obj = {
  quay: "foo",
  key1: "blargh",
  yaya: "foo",
  idnet: "blat",
  blah: "foo",
  hahas: "blargh"
}

const repeated = Object.entries(obj)
  .filter(([key, val]) => val === str)
  .map(([key, val]) => key);

console.log(repeated);

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