code-tutorial.com

The best resources for developers

What is the length of a JavaScript object?

Object.size = function(obj) {
  var size = 0,
    key;
  for (key in obj) {
    if (obj.hasOwnProperty(key)) size++;
  }
  return size;
};

// Get the size of an object
const myObj = {}
var size = Object.size(myObj);
var size = Object.keys(myObj).length;
var person = {
  [Symbol("name")]: "John Doe",
  [Symbol("age")]: 33,
  "occupation": "Programmer"
};

const propOwn = Object.getOwnPropertyNames(person);
console.log(propOwn.length); // 1

let propSymb = Object.getOwnPropertySymbols(person);
console.log(propSymb.length); // 2

Tags: javascript javascript-objects

Source: By Gareth Simpson as answer to the question

This code snippet was collected from stackoverflow, and is licensed under CC BY-SA 4.0


Related code-snippets: