Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over JSON key objects that doesn't have array

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']?

like image 200
ApathyBear Avatar asked May 16 '26 01:05

ApathyBear


1 Answers

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]);
 });
like image 89
madox2 Avatar answered May 17 '26 15:05

madox2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!