Browse Objects Array with Jquery

2

My problem is this, I have an array of colored objects and it is as follows:  [Color [id = 1, CodeColor = Red], Color [id = 2, CodeColor = Green]] And I need to go through that array of colors through the jquery library and paint it in an option of a select, I have tried this code but it gives the following error:

function Color(id, codigoOColor) { 
this.id = id, 
this.codigoOColor = codigoOColor 
}

      function mostrarColores(){
            $.each(colores, function(color){

            let html = '<option>${color.id}</option>';

            $("#ejemploColor").append(html);
        }); 
    }

    mostrarColores();

Can not use 'in' operator to search for 'length' in [Color [id = 1, CodeColor = Red], Color [id = 2, CodeColor = Green]]

    
asked by Francisco José Tiscar Romero 25.02.2018 в 16:11
source

1 answer

2

You would need to add to the .each() feature of JQuery, the index as parameter.

As the documentation says:

  

In the case of an array, the callback is passed an index and its corresponding value each time.

var color1 = {
  id: 1,
  codigoOColor: "Rojo"
}

var color2 = {
  id: 2,
  codigoOColor: "Verde"
}

var arrayObjetos = [color1, color2];

function mostrarColores(){
    $.each(arrayObjetos, function(indice, color){
      let html = "<option>" + color.id + "</option>";
      $("#ejemploColor").append(html);
    }); 
}

mostrarColores();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ejemploColor"></select>

For your specific case, you could also access the object without passing any parameter to the function .each() with the reserved word this .

var color1 = {
  id: 1,
  codigoOColor: "Rojo"
}

var color2 = {
  id: 2,
  codigoOColor: "Verde"
}

var arrayObjetos = [color1, color2];

function mostrarColores(){
    $.each(arrayObjetos, function(){
      let html = "<option>" + this.id + "</option>";
      $("#ejemploColor").append(html);
    }); 
}

mostrarColores();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ejemploColor"></select>

But as indicated in the documentation:

  

The value can also be obtained through the keyword this , but Javascript will always wrap the value of this as an object even if it is a simple string or a numerical value.

    
answered by 25.02.2018 в 16:28