Acdn
Acdn

Reputation: 638

textContent object property doesn't work

var container = document.getElementById("grid-container");
var btn = document.getElementById("btn");
var div;
var reuqest;

function HTTPRequest(url) {
        request = new XMLHttpRequest();
        request.open('GET', url);
        request.onload = function() {
            result(request);            
        };
        request.send();
}

function result(data){
        var res = JSON.parse(data.responseText);
        var array = res.results;
        var myObj = array[0];
        console.log(myObj);
        for (var i = 0; i < Object.keys(myObj).length; i++) {
            div = document.createElement("div");
            div.className = "grid-item";
            container.appendChild(div); 
            for (let key in myObj) {
                console.log(myObj[key]);
                div.textContent = myObj[key];
            }
        }   
}

btn.addEventListener('click', function() {
    HTTPRequest('https://itunes.apple.com/search?term=jack+johnson','author');
});

I am trying to loop through all properties of the object and give the divs I created the text content of each property of the object above.

For some reason I get:

true instead of "track", "song" etc...

Do you know why?

Thanks

Upvotes: 0

Views: 494

Answers (4)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123533

If you're trying to append a div for each of myObj's keys/values, then it should be unnecessary to use two loops to iterate through the keys.

Saving the list of keys from myObj that the for loop is iterating over…

var keys = Object.keys(myObj);
for (var i = 0; i < keys.length; i++) {
    // ...
}

You can get the key for each iteration using the index, i, without needing the additional for..in loop:

var key = keys[i];
div.textContent = myObj[key];

Combined:

function result(data){
    var res = JSON.parse(data.responseText);
    var array = res.results;
    var myObj = array[0];
    var keys = Object.keys(myObj);
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        div = document.createElement("div");
        div.className = "grid-item";
        div.textContent = myObj[key];
        container.appendChild(div);
    }   
}

Upvotes: 1

Saeed
Saeed

Reputation: 5488

Update the innerHTML of div like this instead of textContent and also change = operator to +=.

var myObj = {
  wrapperType: "track",
  kind: "song",
  artistId: 909253,
  collectionId: 879273552,
  trackId: 879273565
}

var div = document.getElementById("test");
var content = ""
for (let key in myObj) {
  content += key + ": " + myObj[key] + "<br>";
}

div.innerHTML = content;
<div id="test">It is a test</div>


Instead of for(let ... in ...) you can use this (According to @Jonathan-Lonowski's answer)

let myObj = {
  wrapperType: "track",
  kind: "song",
  artistId: 909253,
  collectionId: 879273552,
  trackId: 879273565
},
container = document.getElementById("container");

Object.entries(myObj).forEach(function(itm) {
  div = document.createElement("div");
  div.className = "grid-item";
  container.appendChild(div);
  div.textContent = itm[0] + ": " + itm[1];
});
<div id="container"></div>

Upvotes: 1

Ele
Ele

Reputation: 33726

The last key-value pair of every object from that response is:

"isStreamable":true

Therefore, when you're assigning a value to that div as follow div.textContent = myObj[key] you're losing the previously assigned values.

A recommendation is to concatenate the previous values, for example:

div.textContent += separator + myObj[key]

Where separator could be <br>, \n or whatever string you think is suitable.

This is a sample of a response from https://itunes.apple.com/search?term=jack+johnson

enter image description here

Upvotes: 1

andrea06590
andrea06590

Reputation: 1299

You are not looping well on the object here as you use for

You better use this syntax : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/keys

Object.keys(myObj).map((key) => {
    console.log(myObj[key], key)
}

or

Object.keys(myObj).map(function (key) {
    console.log(myObj[key], key)
}

Upvotes: 0

Related Questions