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

192
Visualizações
How do I search a constructor objects properties? JS

See the way I have made the fam object. I can search for this objects user-names and my webpage will display its weight by using this code. As far as I know it is more convenient making objects through a constructor as Dog(). I want my function to be able to iterate through all my objects made through the Dog() constructor such as doggo and doggy and display its weight on my webpage when the user search for the dogs name. How do I do this, if it is even possible?

function Dog(name, weight) {
    this.name = name;
    this.weight = weight;
}

let doggo = new Dog("Spot", "10kg");
let doggy = new Dog("Snoop", "20kg");

const fam = [
    {
        name: "one",
        weight: "1kg"
    },
    {
        name: "two",
        weight: "2kg"
    },
];

function find() {
    var x = String(field.value);
    for (var i = 0; i<fam.length; i++) {
        if (fam[i].name === x) {
            para.textContent = fam[i].weight;
        }
    }
}
btn.addEventListener("click", find);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

One way to do this on the front-end (without using a database) is to add all the objects, in this case the dogs data, inside of an array and then use filter() to select the searched object. Finally return the data to the event listener and create the HTML output.

const input = document.getElementById('input'),
      btn = document.getElementById('btn'),
      container = document.getElementById('container');
      
var dogs = [
  new Dog("spot", "10kg"),
  new Dog("snoop", "20kg"),
  new Dog("snoopy", "100kg")
]

function Dog(name, weight) {
  this.name = name
  this.weight = weight
}

function find(name) {
   let info = dogs.filter(dog => dog.name === name)
   return info[0]
}

btn.addEventListener("click", function(){ 
  let dogInfo = find(input.value), 
      html = `name: ${dogInfo.name} <br> weight: ${dogInfo.weight}`
  container.innerHTML = html
})
<label>Dog name: </label>
<input id="input" type="text" value="spot">
<button id="btn">Show info</button>
<br><br>
<div id="container"></div>

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