take all keys in a json array with js

Asked

Viewed 1,364 times

1

I have an array of json, which currently takes the values this way:

for(element in data){
    data[element]['productor']
}

And my question is this, could I play in html, all my keys and values without necessarily knowing what they are? if I take the ['productor'] on the screen appears like this [object Object] thank you

  • What would be the variable element?

  • As I understand it, data is an array in which its elements are correct objects? if possible post an example of the data array. Ai I get an exact answer on how to solve. I do this type of access daily in my programs.

2 answers

1

Using the method keys class Object you get a array containing all the keys to array past. Then just make your loop on that list:

//declaro o array "x" e insiro alguns valores
var meuArray = [];
meuArray['a'] = 1;
meuArray['b'] = 2;
meuArray['c'] = 3;
meuArray['d'] = 4;

//array de chaves
var chaves = Object.keys(meuArray);

//loop
for (i of chaves) {
  console.log('exemplo 1:', i, meuArray[i]);
}

Using methods such as forEach, You can summarize everything in one prison. To play in HTML, just choose the element that will contain the dice and increment your innerHTML:

var meuArray = [];
meuArray['a'] = 1;
meuArray['b'] = 2;
meuArray['c'] = 3;
meuArray['d'] = 4;

Object.keys(meuArray).forEach(chave => {
  console.log('exemplo 2:', chave, meuArray[chave]);
  document.querySelector('#container').innerHTML += `Chave ${chave}, valor: ${meuArray[chave]} <br>`;
});
<div id="container"></div>

0

{"productor":"Bush Chemist","genre":"UK Roots","singer":"Culture Freeman","rpm":"45","name":"King David Style","label":"Conscious Sounds","description":"teste","release_date":"2003","inch":"12"}

my json comes in this format, but it can see this, fewer records, or more records, needed to take the key and value of it and put it into html. My method of filling the table takes json as parameter

function fillTable(data){
for(element in data){
    //resultSet.innerHTML += JSON.stringify(data[element]);
    resultSet.innerHTML += `
        <label>${JSON.stringify(data[element])}</label>
    `
}

}

that I capture from my requisition

function listAll(){
$.ajax({
    type: "GET",
    dataType: "json",
    url: "http://localhost:8000/findAllSource",
    success:function(data){
        fillTable(data);
    },
    error:function(data){
        alert("Error")
        console.log(data);

    }
});

}

Browser other questions tagged

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