How can I get the value BrandName
in this image using javascript loop.
Asked
Active
Viewed 74 times
-2

Termininja
- 6,620
- 12
- 48
- 49

Nothing
- 2,644
- 11
- 64
- 115
2 Answers
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
-
`Uncaught TypeError: Cannot read property 'length' of undefined ` error. – Nothing Oct 15 '13 at 08:49
-
@Domo Are you sure that variable `CartObject` exists? – VisioN Oct 15 '13 at 08:50
-
Yeah sure VisioN. Anyway I did `console.log(data);` to print out the object in the console image above. – Nothing Oct 15 '13 at 09:16
-
@Domo Aha! Since the root element is `data`, then you need to use `data.CartObject ...` instead. – VisioN Oct 15 '13 at 09:17
-
After adding `data` then `Uncaught TypeError: Cannot read property 'CartLists' of undefined` :/ – Nothing Oct 15 '13 at 09:24
-
@Domo Then please show the rest of your code otherwise we are not able to identify the problem. – VisioN Oct 15 '13 at 09:38
-
let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/39258/discussion-between-domo-and-vision) – Nothing Oct 15 '13 at 09:40
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
-
-
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