How to count the number of keys/properties of an object in JavaScript

2 Answers

0 votes
let obj = {
  id: 383912,
  name: "Albus Dumbledore",
  academicrank: "Professor"
};

let count = 0;
for (k in obj){
  if (obj.hasOwnProperty(k)) {
    count++;
  }
}

console.log(count);

  
  
    
    
/*
run:
    
3
    
*/

 



answered Jan 28, 2021 by avibootz
0 votes
let obj = {
  id: 383912,
  name: "Albus Dumbledore",
  academicrank: "Professor"
};


console.log(Object.keys(obj).length);

  
  
    
    
/*
run:
    
3
    
*/

 



answered Jan 28, 2021 by avibootz
...