-1

I have been on this problem for some hours. The code work like these : someone does an image search, I fetch the answer from an API and I inject the images into a div to present the result. It can vary from 3 to 500 images, it's not fixed.

Except that I cannot manage to display only the right number of images. The problem is in the iteration or the way I present data, but after trying everything and anything I think I need help.

What I receive from the API comes in this form:

{"icon":{"0":"https://address/1587.svg","1":"https://address/3810.svg","2":"https://address/89090.svg","3":"https://address/89400.svg"}}

And here's my (simplified) code:

makeHTTPRequest('GET', url).then((resp) => {
        var parsedResp = JSON.parse(resp);
        var arrayicon = Object.keys(parsedResp).map(function(key) {
            return parsedResp[key]
        });
        injectIcons(arrayicon)
        }; 

        injectIcons = (icons) => {
        let htmlString = '';

        for (var i = 0; i < icons.length; i++) {
            const IconDiv = `src="${icons[i]}"`;
            htmlString = htmlString + IconDiv
        }

        document.getElementById('results').innerHTML = htmlString
    };
Sylv1
  • 3
  • 1
  • 1
    well... first off, you don't have an array object, you just have an object. An array would make more sense in this situation. Is there a chance you can alter the back-end to return a proper array? – Kevin B Mar 06 '19 at 16:26
  • 1
    the use of `for...in` could be useful in your case, see: https://stackoverflow.com/a/684692/9013688 – SylvainF Mar 06 '19 at 16:29
  • Your code should work, it converts your object into an array. The only problem is that you lose the key. You can inject it back into the object before returning it inside your `map()` callback – Mouradif Mar 06 '19 at 16:31

2 Answers2

1

Try to change the code like this:

var response = {"icon":{"0":"https://address/1587.svg","1":"https://address/3810.svg","2":"https://address/89090.svg","3":"https://address/89400.svg"}}

var icons = response.icon;

for (var k in icons ) {
     const IconDiv = `src="${icons[k]}"`;
     htmlString = htmlString + IconDiv
}
Barney
  • 797
  • 1
  • 11
  • 20
0

In this case, a simple while loop could work (assuming you can't change the API to return an actual Array--which would be better):

const data = {"icon":{"0":"https://address/1587.svg","1":"https://address/3810.svg","2":"https://address/89090.svg","3":"https://address/89400.svg"}};

let i = 0;
while (data.icon[i]) {
  console.log(data.icon[i++]);
}

Edit: Your code is actually really close to working. You just need to access parsedResp.icon rather than parsedResp:

var parsedResp = {"icon":{"0":"https://address/1587.svg","1":"https://address/3810.svg","2":"https://address/89090.svg","3":"https://address/89400.svg"}};

var arrayicon = Object.keys(parsedResp.icon).map(function(key) {
  return parsedResp.icon[key]
});

console.log(arrayicon);
Scott Rudiger
  • 1,224
  • 12
  • 16