I have the following JSON list of URLs:
{
"1": [
{"name": "link 1",
"url": "https://url-for-link-1.com"},
{"name": "link 2",
"url": "https://url-for-link-2.com"},
{"name": "link 3",
"url": "https://url-for-link-3.com"}
],
"2": [
{"name": "link 4",
"url": "https://url-for-link-4.com"},
{"name": "link 5",
"url": "https://url-for-link-5.com"},
{"name": "link 6",
"url": "https://url-for-link-6.com"}
]
}
And I have the following javascript:
$.getJSON("/assets/json/resource-links.json", function(data) {
var items = [];
$.each(data, function(id, name, url) {
items.push("<li>" + "< a href='" + url + "'>"
name + "</a>" + "</li>");
});
$("<ul/>", {
html: items.join("")
}).appendTo("#" + id);
});
I have DIVs with ids like this:
<div id="1" class="links">
<ul>
</div>
<div id="2" class="links">
<ul>
</div>
How do I read my list of JSON and put them into the DIVs?
2
Answers
You can simply use a basic function like this
You can try this:
Because you have nested objects you should have nested loops.
When it’s iterating your links you can easily append
li
to the specified
ul
which hasa
as a child in it.