0

I have an object like these

var itemlist= {"50271":2,"50025":1,"90012":3}1

It indicates the reagent to include in a mixture. The property name is the ID of the reagent and the property value the quantity. I would like to generate HTML to display the reagents of a mixture as follows

<img src='50271.jpg'> x 2
<img src='50025.jpg'> x 1
<img src='90012.jpg'> x 3

How can I loop the object to get my expected output?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user3789191
  • 97
  • 10
  • 4
    What you have is an **object**, represented as **object literal**. It is neither an array nor JSON. JSON is *language-independent, textual data-exchange format*, much like XML, YAML or CSV. – Felix Kling Jan 30 '15 at 05:00
  • See [How do I enumerate the properties of a javascript object?](http://stackoverflow.com/q/85992/218196) – Felix Kling Jan 30 '15 at 05:02
  • Also, there is no guarantee what order the properties will be iterated over. If you need a specific order, us an array. – Alexander O'Mara Jan 30 '15 at 05:02
  • sorry I receive it from php json_encode() function – user3789191 Jan 30 '15 at 05:03
  • @user3789191: Doesn't matter where the data came from or in which format. – Felix Kling Jan 30 '15 at 05:03
  • Reopened the dup marking because this question also asks how to generate the desired HTML from the data structure which was not covered in the duplicate. – jfriend00 Jan 30 '15 at 05:14

2 Answers2

1

You'll want to loop through the object like this

for (var key in itemlist) {
  if (itemlist.hasOwnProperty(key)) {
    alert(key + " -> " + itemlist[key]);
  }
}

As shown here: How do I loop through or enumerate a JavaScript object?

Community
  • 1
  • 1
snollygolly
  • 1,858
  • 2
  • 17
  • 31
1

You can loop over the properties of an object using the for (prop in obj) syntax and generate your specific HTML like this:

var itemlist = {"50271":2,"50025":1,"90012":3};
var html = "";
for (var prop in itemList) {
    html += "<img src='" + prop + ".jpg'> x " + itemList[prop];
}
// insert the html somewhere now

P.S. I would guess you may want a <br> after each line.

P.P.S. Data in a javascript object has no guaranteed order so the iteration could end up in any order. You have to use an array if you want a collection in a particular order or you can collect all the keys of the object first and then sort the keys before using them.

jfriend00
  • 683,504
  • 96
  • 985
  • 979