Reputation: 187
I am writing simple changelog for my website that uses github api and appends tag but it doesnt work.
this is my code:
<p id="testing"></p>
<script>
var c = document.getElementById("testing");
$.getJSON("https://api.github.com/repos/test234/test/releases").done(function (json) {
for each (release in json) {
c.appendChild(document.createTextNode(release.tag_name));
}
});
</script>
I think something is wrong with my foreach loop.
Any help is welcome I am stuck here for a long time
Upvotes: 0
Views: 738
Reputation: 112
well, the reason is that your syntax is appropriate for arrays but here json is object so this syntax will not work unless you use Object.Entries
const entries = Object.entries(json)
for(const [index,obj] of entries){
c.appendChild(document.createTextNode(obj.tag_name))
}
or you can use for each method provided for objects like this :
json.forEach(function(value,key,obj){
c.appendChild(document.createTextNode(value.tag_name))
});
Rest is all good , you just need to look for these changes.
Upvotes: 0
Reputation: 28414
This is the right way to use forEach
:
var c = document.getElementById("testing");
$.getJSON("https://api.github.com/repos/4u7157/DOWNLOADS/releases").done(function (json) {
json.forEach((e) => {
console.log(e);
c.appendChild(document.createTextNode(e.tag_name));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="testing"></p>
You can also use JQuery
as follows:
var c = document.getElementById("testing");
$.getJSON("https://api.github.com/repos/4u7157/DOWNLOADS/releases").done(function (json) {
$.each(json, function( index, e ){
console.log(e);
c.appendChild(document.createTextNode(e.tag_name));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="testing"></p>
Upvotes: 3