How to get all matches properties from JSON payload in JavaScript

Viewed 373

I'm new and learning JSON but I have been having an issue with displaying some API results:

$.getJSON(url, function (data) {
    enText = data.data.count;
    arText = data.data.matches.text;
    document.getElementById('verseText').innerHTML = 'Matches: '+enText+'';
    document.getElementById('demo').innerHTML = arText;
})

enText works fine but how do I list the text of all the matches using JSON (above) into an HTML list assuming this is the endpoint: http://api.alquran.cloud/v1/search/abraham/all/en

2 Answers

In your API response matches is an array of object. So you need to iterate the loop to access the text value

$.getJSON("http://api.alquran.cloud/v1/search/abraham/all/en", function (data) {
    enText = data.data.count;
    arText = data.data.matches;

    var li= '';
    for (const x of arText) {
        li+='<li>'+x.text+' <span class="surah">'+x.surah.name+'</span></li>';

    }

    document.getElementById('verseText').innerHTML = 'Matches: ' + enText + '';
    document.getElementById('demo').innerHTML = li;
})

Otherwise if you want a single data, get it using index value. Like below code

arText = data.data.matches[0].text;
document.getElementById('demo').innerHTML = arText;

matches is a JSON Array. You need to iterate over elements and grab text property. Also, remember to declare variables in handler function with const, let or var.

$.getJSON(url, function (data) {
    const enText = data.data.count;
    const arText = data.data.matches
                       .map(m => `<li>${m.text}</li>`)
                       .join("");
    document.getElementById('verseText').innerHTML = 'Matches: '+enText+'';
    document.getElementById('demo').innerHTML = arText;
})
Related