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

121
Visualizações
Get object property value from list of objects without for loop

I have an array of objects in JS

myArray = [
 {name: 'Jim', id: "2"}
 {name: 'Pam', id: "10"}
 {name: 'Dwight', id: "7"}
];

Given I have

var currentID = 2;

And I want to get the name from that array of objects where the id = 2 (all objects will have a unique ID field so there is no issue with multiple objects with the same ID) is there a better way than just doing this

testFunction() {
    var myArray = [
      { name: "Jim", id: "2" },
      { name: "Pam", id: "10" },
      { name: "Dwight", id: "7" },
    ];
    var currentID = "10";
    var currentName = "";

    for (let i in myArray) {
      console.log(i);
      if (myArray[i].id == currentID) {
        currentName = myArray[i].name;
        console.log(currentName);
        break;
      }
    }
  }

This will output "Pam" but i wanted to know if there is a more elegant way to index into that object without the need of a for loop? If not its not too much of an issue as I'm mostly just looking to clean up my code. Thanks!

about 4 years ago · Juan Pablo Isaza
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