0

I have a json object(stored in a separate file) as follows -

"albums":{
"The Wall" : "1979",
"Pulse" : "1995",
"Meddle" : "1971",
"Animals" : "1977"
}

I want this to be dynamically appended in my DOM as below -

<div>
<p>Key on index i<p>
<p>Value on index i<p>
</div>

The entire div structure should render dynamically as many times as there are entries in the JSON ( in this case 4 times ).

$.getJSON("albums.json",
  function (data) {
  $.each(data , function (i) {
     //append logic here
  })

How to achieve this?

1
  • 1
    you didnt give an attempt... Commented Sep 22, 2020 at 15:42

3 Answers 3

2

Here is a non-jQuery answer

const json = {
  "The Wall": "1979",
  "Pulse": "1995",
  "Meddle": "1971",
  "Animals": "1977",
};

for (const key in json) {
  //modify element to append elements
  document.body.innerHTML += `<div><p>${key}</p><p>${json[key]}</p></div>`;
}
<!DOCTYPE html>
<body>
</body>

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

1 Comment

In Jquery we can do something like - var items = <div><p>${key}</p><p>${json[key]}</p></div>; $( "#selector" ).append( items ); I was adding single inverted comma instead of ` ` ! Thanks for your solution, though !
1

Let's separate our concerns. First of all, you need a function with the template:

function myTemplate(key, value) {
    return `
            <div>
                <p>${key}</p>
                <p>${value}</p>
            </div>
           `;
}

So far, so good. Now, let's implement a cycle function:

function myBigTemplate(albums) {
    var output = "";
    for (let albumKey in albums) output += myTemplate(albumKey, albums[albumKey]);
    return output;
}

And then you can put this into a tag, like:

myWrapper.innerHTML = myBigTemplate({"The Wall" : "1979","Pulse" : "1995","Meddle" : "1971","Animals" : "1977"});

5 Comments

while your solution worked, it's a bit lengthy. It can be solved in one line. On a side note, do you know why using after() reverses the order of json items ?
@HarshVardhanBandta it is lengthy in comparison with the solution applied in the accepted answer, but length is less important than 1. the separation of concerns, 2. reusability, 3. clarity. If you have a function for your template, then you know after a single glance what that function is about, you can call it whenever and wherever you need it. The idea is the same with bigTemplate. Yes, this can be solved in one single line, but that's not portable, nor clear. If you work in a team and you leave a code like that, the others will not like it so much.
@HarshVardhanBandta also, imagine the case when you are to do the same thing on 20 separate pages/places. If you apply that one-liner, then you will copy it 20 times, for example. Now, if after a few months that template is to be changed, then you will have to apply the change at 20 places. After time is passing, you will not even be sure where the changes are to be applied. It's much better to have functions for that purpose. You might call the function 20 times, but its content would be implemented exactly once, so it will save you later from large refactorings
@HarshVardhanBandta and your teammates to reading many times the same copy-pasted code. The accepted answer also assumes that you will write this into document.body. It's better to be agnostic about it. With functions, you would know where to put that template into at the time when you implement the call, not at the time you implement the template. So, a one-liner may be shorter than an elegant code, but not necessarily better.
@HarshVardhanBandta as about after(), assuming you speak about api.jquery.com/after it does not necessarily reverse the order. However, if you have an element and you add each item you have after this element, calling after, then it will reverse it, because the latest added element at each step will be after that element and before the earlier added elements.
1

The $.each callback function receives the key and value as parameters. Just append each <p> to the DIV with the results.

$.each(data, function(key, value) {
    $("#outputdiv").append("<p>", { text: key });
    $("#outputdiv").append("<p>", { text: value });
});

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.