Web Analytics

JavaScript Object Methods

Intermediate ~15 min read

Iterating Over Objects

JavaScript provides static methods to iterate over keys, values, or entries of an object.

  • Object.keys(obj): Returns array of keys
  • Object.values(obj): Returns array of values
  • Object.entries(obj): Returns array of [key, value] pairs
HTML
CSS
JS

Cloning and Merging

Object.assign() copies all enumerable own properties from one or more source objects to a target object.

Note: In modern JavaScript, the spread operator ... is often used for this purpose too.

HTML
CSS
JS

Preventing Modifications

Object.freeze() freezes an object. A frozen object can no longer be changed (new properties cannot be added, existing properties cannot be removed or changed).

HTML
CSS
JS

Summary

  • Use Object.keys/values/entries to iterate over object data.
  • Use Object.assign or spread syntax {...obj} to merge or clone objects.
  • Use Object.freeze to make an object immutable.

Quick Quiz

Which method returns an array of a given object's own enumerable property names?

A
Object.values()
B
Object.entries()
C
Object.keys()
D
Object.names()