1

I want to display the incoming messages on a webpage. I have a url pointing to a JSON-file, the data looks like this ...

[
    {
      "created_at": "2019-06-08T10:30:52Z",
      "data": {
        "name": "Me",
        "email": "[email protected]",
        "is-org-bedrijf": "on",
        "org-bedrijf": "",
        "onderwerp": "meer info",
        "bericht": "bericht",
        "job-logo-deadline": "",
        "digitaal-deadline": "",
        "drukwerk-deadline": "",
        "flex-floc-kleuren": "transparant",
        "job-flex-floc-deadline": "",
        "andere-beschrijving": "",
        "andere-deadline": "",
        "g-recaptcha-response": ""
      },
      "folder": null,
      "id": 3250210,
      "referrer": "https://lennertderyck.be/contact/form",
      "request_ip": "78.23.211.248",
      "spam": null
    }
]

How can i access the information in a javascript loop? Displaying the data is not the problem, it's accessing the data in the nested object.

This is what I tried

 fetch('file.json')
            .then(function (response) {
                return response.json();
            })
            .then(function (source) {
                appendData(source);
            })
            .catch(function (err) {
                console.log('error: ' + err);
            });
        function appendData(source) {
            var mainContainer = document.getElementById("myData");
            for (var i = 0, il = source.length; i < il; i++) {
                    var div = document.createElement("div");
                    div.innerHTML = 'Id: ' + source[i].id;
                    mainContainer.appendChild(div);
                for (var j = 0; jl = source[i].data.length; j++) {
                    console.log(source[i].data[j].name)
                }
            }
        }

1 Answer 1

1

Because that's not how you iterate through an object. Do it with a for...in loop like so:

for (var item in source[i].data) {
    console.log(source[i].data[item].name);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Now i just get 14 times undefined in the console. But when I remove name, and just use source[i].data[item] all the data is shown correctly.

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.