Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 156 ยท Objects

Working with Objects

List and transform object data with Object.keys, values, entries and fromEntries, merge with assign, check keys with hasOwn and in, and freeze objects.

In the Objects lesson you created objects and read their properties one at a time. Real programs often need to work with all the properties at once: show every setting in a form, total up a price list, rename keys from an API response, or merge defaults with user choices.

JavaScript's built-in Object provides static helper functions for exactly these jobs. This lesson covers the ones you'll use constantly โ€” Object.keys(), values(), entries() and fromEntries() โ€” plus Object.assign(), the in operator and Object.hasOwn() for checking keys, delete for removing them, and Object.freeze() for protecting an object from changes.

Listing keys, values and entries

Three functions turn an object into an array you can loop over or process with array methods:

  • Object.keys(obj) โ€” an array of the property names.
  • Object.values(obj) โ€” an array of the values.
  • Object.entries(obj) โ€” an array of [key, value] pairs.

All three include only the object's own, enumerable, string-keyed properties โ€” which, for ordinary objects you create yourself, simply means "the properties you added". They follow the property order rules: integer-like keys first, then the rest in insertion order.

JS keys, values and entries

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The for...of loop uses [fruit, count] to unpack each pair into two variables. That syntax is destructuring, the topic of the next lesson; for now, read it as "name the first item fruit and the second count".

for...in vs Object.keys(). A for...in loop also visits inherited enumerable properties, while Object.keys() lists only the object's own. For plain data objects they usually match, but Object.entries() with for...of is the safer, more common choice today. See for...of and for...in.

Building objects with Object.fromEntries()

Object.fromEntries() is the reverse of entries(): it takes a list of [key, value] pairs and builds an object. Combined, the two let you transform an object with array methods โ€” turn it into entries, map or filter them, then turn the result back into an object:

JS Transforming objects through entries

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The exchange rate here is made up for the example. The pattern โ€” entries, transform, fromEntries โ€” is the standard way to "map over an object", because objects don't have their own map() method. (([, price]) skips the first item of each pair, since the filter only needs the price.)

Merging with Object.assign()

Object.assign(target, ...sources) copies every own enumerable property from the sources into the target, from left to right, so later sources overwrite earlier ones. It changes the target and also returns it:

JS Object.assign() and spread

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both Object.assign() and spread make shallow copies: nested objects are shared by reference, not duplicated. If defaults contained an editor: { tabs: 2 } object, settings.editor would be the very same object. The lesson Copying Objects: Shallow and Deep explains how to handle that.

Most new code uses spread for merging into a fresh object. Object.assign() is still the right tool when you deliberately want to add properties to an existing object.

Checking whether a key exists

Comparing to undefined seems like an easy test, but it can't tell "missing" from "present with the value undefined". Use one of these instead:

  • "key" in obj โ€” true if the property exists on the object or anywhere in its prototype chain.
  • Object.hasOwn(obj, "key") โ€” true only if the object has the property itself. Added in ES2022 and supported in all modern browsers; older code uses obj.hasOwnProperty("key") for the same check.
JS in vs Object.hasOwn()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For plain data objects, Object.hasOwn() is usually what you mean. in is useful when inherited properties count too, such as checking whether an object supports a method.

Removing properties with delete

The delete operator removes a property from an object entirely. Setting it to undefined is different: the key stays, just with an empty value.

JavaScript
const draft = { title: "Hi", body: "...", tempId: 99 };

draft.body = undefined;
Object.keys(draft);   // ["title", "body", "tempId"] โ€” body still listed

delete draft.tempId;
Object.keys(draft);   // ["title", "body"]
"tempId" in draft;    // false

delete returns true when it succeeds (also when the property didn't exist). It only affects the object's own properties, and it can't remove variables. If you want a copy without some keys instead of changing the original, the rest syntax in Spread and Rest does it neatly.

Protecting objects: freeze and seal

Sometimes an object should never change after it is created โ€” configuration, lookup tables, constants. Object.freeze(obj) makes it read-only: no adding, changing or deleting properties.

JS Object.freeze()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two things to remember: in sloppy scripts, writes to a frozen object fail silently, while strict code (including modules and classes) throws a TypeError. And freeze() is shallow, so nested objects need to be frozen separately if they must not change.

There are two milder versions:

Function Add properties Delete properties Change values
Object.preventExtensions(obj) No Yes Yes
Object.seal(obj) No No Yes
Object.freeze(obj) No No No

Remember that const is unrelated: it stops reassigning the variable, while freeze() stops changing the object.

A practical example: counting

Objects make great tallies. Combine a loop with bracket notation and the ?? operator to count anything:

JavaScript
const votes = ["tea", "coffee", "tea", "juice", "tea", "coffee"];
const tally = {};

for (const vote of votes) {
  tally[vote] = (tally[vote] ?? 0) + 1;
}

tally; // { tea: 3, coffee: 2, juice: 1 }

const [winner] = Object.entries(tally).sort((a, b) => b[1] - a[1]);
winner; // ["tea", 3]

For grouping whole items rather than counting them, the newer Object.groupBy() does the job in one call; it's covered in Array Recipes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Object.entries({ a: 1, b: 2 }) return?

    entries() returns an array of [key, value] pairs. keys() and values() return the first two options.
  2. 2. How do you apply a transformation to every value of an object and get an object back?

    Objects have no map() method. Convert to entries, transform with the array method, then rebuild with fromEntries().
  3. 3. const p = { x: undefined }; โ€” which check returns false?

    x is an own property (with the value undefined), but toString is inherited from Object.prototype, not owned by p.
  4. 4. What does Object.assign(a, b) do to a?

    The first argument is the target and is modified. Pass {} as the target, or use spread, to leave existing objects untouched.
  5. 5. After const cfg = Object.freeze({ db: { port: 5432 } });, what happens with cfg.db.port = 1;?

    Object.freeze() only protects the object's own properties. The nested object is a separate object that stays mutable.

Summary

  • Object.keys(), values() and entries() turn an object's own properties into arrays you can loop over and process.
  • Object.fromEntries() builds an object from pairs; entries โ†’ map/filter โ†’ fromEntries transforms objects.
  • Object.assign(target, ...sources) merges into and returns the target; spread { ...a, ...b } is the common way to merge into a new object. Both are shallow.
  • Use Object.hasOwn() for own keys and in when inherited keys count; don't rely on === undefined.
  • delete removes a property completely; Object.freeze() makes an object read-only (shallowly), with seal() and preventExtensions() as milder options.

Next: Destructuring โ€” unpacking values from objects and arrays into variables.