0

i have the following object in javascript:

objectX which is an

Object {names : Array[14]}

im trying to get the length of this, but it returns undefined when i use objectX.length?

Im trying it in chrome debugger, and googling, anyone out there quickly let me know plz.

asked Dec 3, 2013 at 15:28
4
  • Do you want the number of properties in Object, or the length of Object.names? Commented Dec 3, 2013 at 15:31
  • length of names @BenM Commented Dec 3, 2013 at 15:32
  • See the answer posted already, then. Commented Dec 3, 2013 at 15:33
  • objectX | objectx? Commented Dec 3, 2013 at 15:41

3 Answers 3

7
object.names.length

OR

object['names'].length
answered Dec 3, 2013 at 15:29

3 Comments

If i use objectx.names it returns undefined
Then your object is defined differently than the code you presented. (you'll need to replace "object" with whatever variable name you're using... perhaps objectx.names.length)
Okay if i use Object.keys(objectx).length, this returns me 1. But i want the length of names. Which it says is an array in chrome
4

From the output it seems that the property name is 'name '. See the differences in the console output:

> console.log({names: []});
Object {names: Array[0]}
> console.log({'names ': []});
Object {names : Array[0]} // <- this looks like what you have
// ^ note the space

So you'd have to do:

obj['names '].length

I suggest to fix the property name though, so that you can use obj.name.length instead.

answered Dec 3, 2013 at 15:43

2 Comments

thankyou, i just didn't think of that! grrrr spent last 20 minutes not even looking at that!
Next time you know ;)
0

Fix your object notation:

var obj = {name:Array(14)};
alert(obj.name.length);
var obj = {name : [1, 2, 3, 4]};
alert(obj.name.length);

Fiddle

answered Dec 3, 2013 at 15:48

4 Comments

Object {names : Array[14]} is the output in Chrome's console. It's not actually JS code.
@FelixKling Ok, I misunderstood. Though I didn't think a space was valid in a property name.
You can use any string as property name. But if the property is not a valid identifier, then you cannot use dot notation (a.b) to access it, you have to use bracket notation (a['b']).
@FelixKling interesting. I learned something new today, thanks!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.