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?

6
  • 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. Commented Jan 30, 2015 at 5:00
  • See How do I enumerate the properties of a javascript object? Commented Jan 30, 2015 at 5:02
  • Also, there is no guarantee what order the properties will be iterated over. If you need a specific order, us an array. Commented Jan 30, 2015 at 5:02
  • sorry I receive it from php json_encode() function Commented Jan 30, 2015 at 5:03
  • @user3789191: Doesn't matter where the data came from or in which format. Commented Jan 30, 2015 at 5:03

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

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.