+ 3

Object amount

Letā€™s say I have an object... var food = {1: ā€œbananaā€, 2: ā€œappleā€,} How do I count the amount of food using only one line of code? Other languages example: #words #words will output 2

25th Nov 2017, 8:57 AM
Norberttony
Norberttony - avatar
4 Answers
+ 3
Javascript object not like array, does not have a length property. You need to get the keys array of the object, then only get the length of the keys array. eg. console.log(Object.keys(food).length);
25th Nov 2017, 10:32 AM
CalviÕ²
CalviÕ² - avatar
+ 2
I tried .length, and it caused an error.
25th Nov 2017, 9:37 AM
Norberttony
Norberttony - avatar
+ 1
return food.length;
25th Nov 2017, 9:09 AM
Momo Belia
Momo Belia - avatar
0
what error ? can you show me?
25th Nov 2017, 9:38 AM
Momo Belia
Momo Belia - avatar