I want to showing data like this:
Fire Forest : 60
Earthquake : 50
I've trying some method, but still get confused and showing not what I want. By the code below:
$.getJSON(urlLink, function(data){
var disasterData = '';
$("#currentChartDisaster").empty();
$("#currentChartDisaster").append("<h2>Jumlah Bencana Terjadi Bulan Ini</h2>");
$.each(data,function(key, value){
disasterData = '<h3>' value '</h3>';
})
$('#currentChartDisaster').append(disasterData);
});
It's only showing like this :
Earthquake, Fire Forest. 60, 50
I have JSON format like this:
{
"disasterName":[
"Fire Forest",
"Earthquake"
],
"disasterCount":[
"60",
"50"
]
}
CodePudding user response:
Given the format of your data where the name/count are in separate arrays, you can use a basic for
loop to get the index for each disaster, to get the corresponding name/count based on that index
data.disasterName[i] " : " data.disasterCount[i]
This assumes there's the same number of disaster names as counts and that the associated values are in the same order - eg count[0] is for forest fires.
var data = {
"disasterName": [
"Fire Forest",
"Earthquake"
],
"disasterCount": [
"60",
"50"
]
};
var count = data.disasterName.length;
var html = '';
for (let i = 0; i < count; i) {
html = "<h3>" data.disasterName[i] " : " data.disasterCount[i] "</h3>";
}
$("#output").append(html);
h3 { font-size: 1em; font-weight: normal; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='output'></div>
As you can change the format, you could make it more object-like, eg an array of:
{
"name": "Forest Fire",
"count": 60
},
then the js will be closer to your initial attempt as you don't need to loop the index and can use a .forEach() or .map()
var data = {
"disasters": [
{
"name": "Forest Fire",
"count": 60
},
{
"name": "Earthquake",
"count": 50
}
]
};
// forEach
//var html = '';
//data.disasters.forEach(disaster => {
// html = "<h3>" disaster.name " : " disaster.count "</h3>";
//});
// or map
var html = data.disasters.map(disaster =>
"<h3>" disaster.name " : " disaster.count "</h3>"
);
$("#output").append(html);
h3 { font-size: 1em; font-weight: normal; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='output'></div>