Navigate array of objects until they reach their properties in js

1

I have a function in which I pass an element of type string and I want to compare it with a property that each object that makes up the Array have. If it matches, it returns true and false.

function Carta(id, marca, puntos) {
    this.id = id;
    this.marca = marca;
    this.puntos = puntos;

    //GETTER
    this.getId = function () {
        return this.id;
    }

    this.getMarca = function () {
        return this.marca;
    }

    this.getPuntos = function () {
        return this.puntos;
    }
}

lambo1 = new Carta("lambo1", "lamborghini", 25);
lambo2 = new Carta("lambo2", "lamborghini", 25);
bmw1 = new Carta("bmw1", "bmw", 25);
bmw2 = new Carta("bmw2", "bmw", 25);
volks1 = new Carta("volks1", "volkswagen", 25);
volks2 = new Carta("volks2", "volkswagen", 25);
nissan1 = new Carta("nissan1", "nissan", 25);
nissan2 = new Carta("nissan2", "nissan", 25);

function verificarCampo(elemento){
    for (i=0; i<=baraja.length; i++) {
        if(baraja[i]."objeto"."elementoObjeto"==elemento){
            return true;
        }
        else{
            return false;
        }
    }
}

But in the check "if (shuffles [i]." object "." elementObject "== element)" I do not know how to write it correctly since each object has a different name ...

Within each object its properties have the same names. Does anyone know how I could do it?

    
asked by Eduardo 24.11.2017 в 17:55
source

2 answers

0

Assuming the deck is an array that groups the cards:

var baraja=[];
baraja.push( new Carta("lambo1", "lamborghini", 25));
baraja.push( new Carta("lambo2", "lamborghini", 25));
baraja.push( new Carta("bmw1", "bmw", 25));
baraja.push( new Carta("bmw2", "bmw", 25));
baraja.push( new Carta("volks1", "volkswagen", 25));
baraja.push( new Carta("volks2", "volkswagen", 25));
baraja.push( new Carta("nissan1", "nissan", 25));
baraja.push( new Carta("nissan2", "nissan", 25));

And you want a function that verifies that if the "nissan2" card is in the deck, you would do

function cartaExiste(id_carta){
    var existe=false;
    for (i=0; i < baraja.length; i++) {
        if(baraja[i].getId() == id_carta ){
            existe = true;
        }
    }
    return existe;
}

Note that the loop ends in i < baraja.length and not in i <= baraja.length . The arrays start at zero.

There's a smarter way to do it than using array.filter

function cartaExiste(id_carta){
    var matching = baraja.filter(function(carta) {
      return carta.getId() == id_carta;
    });
    return matching.length>0;
}
    
answered by 24.11.2017 / 18:13
source
0

I could have used the find () method to compare the getter with the value passed by parameter, and if returns undefined is because that element is not found, with this last we could check for return ;

function verificarCampo(elemento){
    let obj = baraja.find(o => o.getId() === elemento);
    return obj !== undefined;
}
    
answered by 24.11.2017 в 18:24