DEV Community

Discussion on: How to Get an Object Length

Collapse
 
nickymeuleman profile image
Nicky Meuleman • Edited

Great writeup!

The enumerable and Symbols parts were especially excellent.

This made me play around with your example code a bit and I have a question.

const numbers = {one: '1️⃣'};

Object.defineProperty(
  numbers,
  Symbol.for('two'), {
    value: '2️⃣',   
    enumerable: false // default value
  },
);

const enumerableLength = Object.keys(numbers).length; // 1
const symbolLength = Object.getOwnPropertySymbols(numbers).length; // 1
const totalObjectLength = enumerableLength + symbolLength; // 2

Enter fullscreen mode Exit fullscreen mode

How should I handle this case where I don't want the symbol to get counted?

edit:
Came up with this, other solutions?

const enumerableSymbolLength = Object.getOwnPropertySymbols(numbers).filter(key => numbers.propertyIsEnumerable(key)).length // 0
const totalObjectLength = enumerableLength + enumerableSymbolLength; // 1
Enter fullscreen mode Exit fullscreen mode
Collapse
 
samanthaming profile image
Samantha Ming

If you only want the enumerable properties without the symbols. The Object.keys method should just work, since it doesn't include that. If I misunderstood your questions, please follow up 🙂

Collapse
 
nickymeuleman profile image
Nicky Meuleman • Edited

All enumerable properties, including ones with Symbols as keys.
Excluding all non-enumerable properties.

an object with:
1 enumerable property with string as key,
2 non-enumerable properties with a string as key,
1 enumerable property with Symbol as key
1 non-enumerable properties with Symbol as key.

Should return 2 as total length. (1 for string key and 1 for Symbol key)