+ 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 Respostas
+ 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