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.
user1555190user1555190
asked Dec 3, 2013 at 15:28
3 Answers 3
object.names.length
OR
object['names'].length
answered Dec 3, 2013 at 15:29
3 Comments
user1555190
If i use objectx.names it returns undefined
adamb
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
)user1555190
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
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
user1555190
thankyou, i just didn't think of that! grrrr spent last 20 minutes not even looking at that!
Felix Kling
Next time you know ;)
Fix your object notation:
var obj = {name:Array(14)};
alert(obj.name.length);
var obj = {name : [1, 2, 3, 4]};
alert(obj.name.length);
answered Dec 3, 2013 at 15:48
4 Comments
Felix Kling
Object {names : Array[14]}
is the output in Chrome's console. It's not actually JS code.Dave Rager
@FelixKling Ok, I misunderstood. Though I didn't think a space was valid in a property name.
Felix Kling
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']
).Dave Rager
@FelixKling interesting. I learned something new today, thanks!
lang-js
Object
, or the length ofObject.names
?objectX
|objectx
?