2

I have the following JSON:

basket = {
    "Items": 3,
    "Item": {
          "iPhone 6": {
              "productId": 227,
         "url": "http://example.com/iphone6",
         "price": 299.99
           },
          "Solio Mono Solar Charger": {
          "productId": 655,
          "url": "http://website.com/solio_charger.html",
          "price": 29.95
           },
           "24 Month Warranty Package": {
             "productId": 681,
          "url": "http://website.com/24_month_warranty.html",
          "price": 129.95
           }
      },
    "Total": 459.89
}

I want to loop over the objects in basket['Item'], but the JSON does not inherently provide an array to do so, what is the best way to loop over the objects in basket['item']?

2
  • There's plenty of ways to do this - what have you tried? Commented Feb 26, 2016 at 19:41
  • You can check this thread: stackoverflow.com/questions/1078118/… Commented Feb 26, 2016 at 19:41

3 Answers 3

7

You can use Object.keys() to get all property names of object and then iterate it with Array.prototype.forEach():

 Object.keys(basket.Item).forEach(function(key) {
      console.log(item);
      console.log(basket.Item[key]);
 });
Sign up to request clarification or add additional context in comments.

Comments

5

You can use for...in for that.

var obj = {
  cat: 'meow',
  dog: 'woof'
}

for (attr in obj) {
  console.log(attr + ': ' + obj[attr])
}

Which will appropriately log:

cat: meow
dog: woof

Here's a JSFiddle for your object.

You can also use Object.keys() but it's only supported in IE >= 9.

Comments

1

You can use for in:

for (var property in basket['Item']) {
    var value = basket['Item'][property];
    console.log(property + ':');
    console.dir(value);
}

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.