chiba muller chiba muller - 2 months ago 7
Javascript Question

Loop to collect all the image properties from array of objects

What I am trying to do is "Get the image URLs from all numbers and display them in console" using a loop to collect all the image properties from each number.

What I have so far is:

$.get("file.json", function(start){
for(var numbers in start.data){
console.log(numbers)
}
})


It displays the numbers. I don't know what to do next.

This is my JSON data.

"id": 2237,
"username": "mark",
"bc": "NBC",
"rap": 987,
"count": 4,
"uniqueCount": 4,
"data": {
"1533893": {
"id": 1533893,
"name": "Bluesteel Egg of Genius",
"bc": "NBC",
"type": "hat",
"originalPrice": 0,
"image": "https://t3.rbxcdn.com/1e8ba7802f5ab0cdd1fffb936e761aff",
"rap": 196,
"stock": 0,
"userAssetId": {
"16611316": 0
}
},
"5785985": {
"id": 5785985,
"name": "Rusty Tetramino of Competence",
"bc": "NBC",
"type": "hat",
"originalPrice": 0,
"image": "https://t6.rbxcdn.com/04cd63b742f1b88de64672a79d192e58",
"rap": 182,
"stock": 0,
"userAssetId": {
"16611313": 0
}
},
"5786026": {
"id": 5786026,
"name": "Silver Tetramino of Accomplishment",
"bc": "NBC",
"type": "hat",
"originalPrice": 0,
"image": "https://t1.rbxcdn.com/c311faa4a2f6ec380d6c86b95171b69a",
"rap": 252,
"stock": 0,
"userAssetId": {
"16611314": 0
}
},
"5786047": {
"id": 5786047,
"name": "Gold Tetramino of Mastery",
"bc": "NBC",
"type": "hat",
"originalPrice": 0,
"image": "https://t3.rbxcdn.com/54ec21da8b3962aca7c1bd9214cd6f2b",
"rap": 357,
"stock": 0,
"userAssetId": {
"16611315": 0
}
}
},
"success": true


}

Question

How can I enhance my code to achieve my requirements?

Answer

You can iterate the object using Object.keys

 Object.keys(start.data).forEach(function(key) {
    console.log(key, start.data[key].image); 
 });

In case that you are unsure if the object has an image property then you can add a check to avoid errors:

Object.keys(start.data).forEach(function(key) {
  if (start.data[key].image) {
    console.log(key, start.data[key].image);
  }         
});