1

When I query the following API.

var json_obj;
$.getJSON("https://46il4vpccl.execute-api.eu-west-2.amazonaws.com/api/secblogfeed/Threatpost", function (data) {
json_obj = data;
});

I can then see the output using the following approach:

alert(json_obj.Items[0].title);
alert(json_obj.Items[0].link)

What I would like to do is return a list of all title and link as a hyperlink as follows by expanding on the code above:

(Desired output HTML would be like this on a web page).

<p><a href="link string here">title string here</a></p>
<p><a href="link string here">title string here</a></p>
etc

I have tried various ways of looping through this data but would like to learn how to do this efficiently. Thanks for any help.

1
  • 1
    loop throught item array and generate html using jquery Commented Aug 2, 2019 at 8:01

2 Answers 2

3

To achieve this you can use a loop through the Items property of the response to build the required HTML. The most succinct way of doing this would be to use map(), like this:

$.getJSON("https://46il4vpccl.execute-api.eu-west-2.amazonaws.com/api/secblogfeed/Threatpost", function(data) {
  var html = data.Items.map(function(item) {
    return `<p><a href="${item.link}">${item.title}</a></p>`;
  });
  $('#yourContainingElement').append(html);
});

Also note that I am getting a CORS error when making a request to that domain. I'd suggest you check that the request works for you.

Sign up to request clarification or add additional context in comments.

Comments

0

You can try to map the original object to a new filtered object like this

let list = json_obj.Items.map(e=>{
  return {title:e.title,link:e.link}
});

You can then use a for loop to generate elements for each element of this object as

function generateElement(item) {
    let p = document.createElement("p");
    let a = document.createElement("a");
    a.setAttribute("href",item.link);
    a.innerText = a.title;
    p.appendChild(a);
    return p;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.