How to print the prefixes together with the array?

Asked

Viewed 90 times

0

I would like a help to print an array with its prefixes.

this.prefixo = [
        {
            "E01":[{"name":"Teste01"}],
            "E02":[{"name":"Teste02"}]
        }
    ];

I would like to print the prefixes and the names related to each prefix.

  • 1

    But can you have more than one prefix name? It seems that there are too many arrays in your code, it could be a simple object.

  • In this case it is a list of prefix E0.... where there is data within each E0.... of this. I need in html to select this prefix where through the prefix I select it will enable or not some fields.

  • 1

    Print? On a sheet? On the screen in an Alert? Move the view model to an html table?

1 answer

1


Look, what you have there is an array with an object inside: [ { } ]. There is nothing else in this array, but I will assume that there may be other objects with the same schema. And this object has keys (like E01) pointing to other arrays, each with another object inside, which has the name and value. You will need to use nested loops/loops to catch all this:

this.prefixo = [
        {
            "E01":[{"name":"Teste01"}],
            "E02":[{"name":"Teste02"}]
        }
    ];


// Variáveis para organizar o código
var i, j, chave, objetoExterno, objetoInterno, arrayInterna

// Para cada item na array mais externa
for(i=0; i<this.prefixo.length; i++) {
  

  // o objetoExterno é o que contém as chaves;
  // no exemplo só tem 1, mas como é um array deles,
  // pode haver mais
  objetoExterno = this.prefixo[i];
  
  
  // Vamos ver quais são as chaves desse objeto
  // e o que elas contêm
  for(chave in objetoExterno) {
    
    // Cada chave do objeto contém uma array
    arrayInterna = objetoExterno[chave];
    
    // Pode haver vários itens dentro de cada array
    for(j=0; j<arrayInterna.length; j++) {
        
      
      // Cada item dessa array é um objeto que contém um nome
      objetoInterno = arrayInterna[j];
      
      imprime('Encontrado o nome ' + objetoInterno.name + ' na chave ' + chave);
      
    }
    
  }
  
}


// Imprime na janela de "resultado" do exemplo
function imprime(txt) {  
  document.body.innerHTML += txt + '<br>'; 
}

With this data, arrays are unnecessary. If the data were like this:

this.prefixo = {
  "E01":"Teste01",
  "E02":"Teste02"
};

You could easily access each name by prefix:

alert(this.prefixo.E01);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.