-2

How can I get the value BrandName in this image using javascript loop.

image

Termininja
  • 6,620
  • 12
  • 48
  • 49
Nothing
  • 2,644
  • 11
  • 64
  • 115

2 Answers2

2

UPDATED: Since data variable you use to display the response is already a CartObject then use:

for (var i = 0, len = data.CartLists.length; i < len; i++) {
    console.log( data.CartLists[i].Item.BrandName );
}
VisioN
  • 143,310
  • 32
  • 282
  • 281
0

An alternative to the one VisioN said is the following:

for (var CartItemId in CartObject.CartLists) {
     Console.log(CartObject.CartLists[CartItemId].Item.BrandName);
}

However, If you would attach an Prototype to the JSON object, you could obtain an Object in the for-loop instead of an Integer (Number).

for (var CartItem in CartObject.CarLists) {
     Console.log(CartItem.Item.BrandName);
}

Note that if you are going to make everything right, you should insert the following in the for-loop:

if (CartObject.CarLists.hasOwnProperty(CartItem)) {
    Console.log(CartItem.Item.BrandName);
}

This example will work, but as seen in the comments below. The use of it is not what it is designed for. The For-In loop is designed to loop over Object properties, not Array items.

lt.kraken
  • 1,287
  • 3
  • 10
  • 27
  • [It is always better to loop arrays using plain `for` loop instead of `for .. in` loop.](http://stackoverflow.com/a/3010848/1249581) – VisioN Oct 15 '13 at 08:51
  • In my opinion it doesn't really matter aslong you include the 'hasOwnProperty' method. – lt.kraken Oct 15 '13 at 08:53
  • Meaning that it is faster and easier to use 'numeric' iteration `=)`. – VisioN Oct 15 '13 at 08:58
  • True, but it is an alternative. Next to this, the for..in might be of wrong use in here. Its looping through an array, not the properties. It will work, but it is not what for..in is designed for. – lt.kraken Oct 15 '13 at 09:03