0

I'm trying to print the length of this JSON Object to the console but I keep receiving 'undefined'.

This is being JSON encoded in PHP and then returned via ajax to an anonymous function as 'msg'

{"1":{"item_id":"shirt_straight--small","quantity":5},"2":{"item_id":"shirt_straight--medium","quantity":"2"}}

Printing to console:

console.log(msg.length); //undefined
console.log(msg[1].item_id); //shirt_straight--small

I'm able to print the value of msg[1].item_id but I'm not able to get the length via msg.length

Thanks for your help.

user2864740
  • 60,010
  • 15
  • 145
  • 220
ajodom10
  • 141
  • 1
  • 4
  • 12

2 Answers2

0

Arrays have a length property. Objects do not (by default). I think the problem is on the php end ... You should be encoding an array and sending that back instead. Arrays are zero-indexed, so that may be the problem. Perhaps json_encode(array_values($msg)).

If your keys are correct after all, give Object.keys(msg).length a shot.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

This can be a duplicate of Length of a JavaScript object

Look at the accepted answer.

BTW, just found googling "javascript object length" ;)

EDIT:

It's true that objects don't have a length property, and you can get the length with Object.keys(foobar).length, but it won't work in IE8 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)

Community
  • 1
  • 1
danikaze
  • 1,550
  • 2
  • 16
  • 34