get all keys in an array of json with js

1

I have an array of json, which I currently get values like this:

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

And my question is the following, would I have like to play in html, all my keys and values without necessarily knowing what they are? if I take the ['productor'] on the screen it appears [object Object] Thank you

    
asked by anonymous 28.04.2018 / 06:12

2 answers

1

Using the keys method of the Object class you get an array containing all the keys of the array passed. Then you just have to loop through this 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 like forEach , you can summarize everything in a single string. To play in HTML, simply choose the element that will contain the data and increment its 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>
    
28.04.2018 / 07:27
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 come from this, less records, or more records, needed to get the key and value from it and put in the html. My method of populating table receives json as parameter

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

}

I capture my request

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);

    }
});

}

    
30.04.2018 / 03:35