Skip to content
Tutorials Center
My learning

Topics

Lesson 154 of 156 ยท Practice and Review

Object Recipes

Ready-to-use JavaScript object recipes: flatten nested objects, filter and map values, pick or omit keys, swap keys and values, parse query strings, compare objects.

Arrays have map, filter and reduce. Objects have no such methods, yet you transform them just as often: keep only some properties, rename keys, turn a query string into data, or flatten a nested settings object into one level for a form. The trick is always the same. Convert the object to an array of entries, do the work with array methods, and convert back.

This lesson is a cookbook of those object patterns. Each recipe is short, runs in the editor, and tells you which trap to avoid. If you need a refresher first, read Working with Objects and Copying Objects.

The entries round trip

Almost every recipe below is built on two functions. Object.entries(obj) returns an array of [key, value] pairs, and Object.fromEntries(pairs) builds an object from such pairs. Between them you can use any array method.

JS Filter and map an object

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

No output.

None of these helpers changes the original object. They build a new one, which keeps your data predictable.

Pick and omit properties

Sometimes you want only a few properties: the public fields of a user, the keys a form is allowed to update. Pick keeps the named keys; omit keeps everything except them. Checking with in or Object.hasOwn avoids creating keys that were never there.

JS Pick and omit

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

No output.

Use an allow-list (pick) rather than a deny-list (omit) for anything security related, such as which fields a client may change. A deny-list silently lets through every field you add later.

Swap keys and values

Inverting an object turns a lookup from "code to name" into "name to code". The catch: values become keys, so duplicate values collapse into one key, and every key becomes a string.

JS Invert an object

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

No output.

Dynamic keys and arrays to objects

A computed property name in square brackets lets a variable decide the key while you build an object. It is how you write { [field]: value } for a form that updates whichever field changed. To turn an array into an object, pick a key function and let fromEntries (or reduce) do the rest.

JS Computed keys and array to object

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

No output.

If keys can be anything (including "__proto__" or non-strings), use a Map instead of an object.

Flatten a nested object

Flat key-value pairs are easier to put in a form, a CSV file or a query string. Flattening walks the object and joins the path with dots: { a: { b: 1 } } becomes { "a.b": 1 }. The reverse, unflattening, splits each key and rebuilds the nesting.

JS Flatten and unflatten

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

No output.

Arrays are kept whole here. Treat them as leaves, or flatten them with index keys (tags.0) if you need to. Keys that already contain a dot would be ambiguous, so choose a separator that your keys never use.

URL query strings to objects

Query strings (?q=js&page=2) look like objects but arrive as text. URLSearchParams parses them for you, and Object.fromEntries turns the result into an object. Values are always strings, so convert numbers yourself.

JS Query string to object and back

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

No output.

For URLs in general, see URLs, Location and History.

Compare objects

=== on objects compares identity, not contents: two objects with the same properties are still different objects. A shallow comparison checks the top-level keys and compares values with ===. A deep comparison also looks inside nested objects and arrays.

JS Shallow and deep equality

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

No output.

This version does not handle Date, Map, Set, cyclic references or class instances. For quick checks of JSON-like data, comparing JSON.stringify output is tempting but fragile, because it depends on key order. In tests, use your test library's equality matcher.

Prototype pollution. Never copy or merge keys from untrusted input with a loop like target[key] = source[key] without checking the key. A key named __proto__ or constructor can change what every object inherits. Use Object.hasOwn, skip those key names, or store the data in a Map. See Security.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which expression keeps only the entries of obj whose value is greater than 10?

    Objects have no filter method. Convert to entries, filter the array, then rebuild an object with Object.fromEntries. The last option stops at an array of pairs.
  2. 2. What does inverting { a: 1, b: 1, c: 2 } with the simple entries swap produce?

    An object cannot hold two keys with the same name, so the later entry replaces the earlier one. To keep both, group the keys into arrays.
  3. 3. What is the result of shallowEqual({ a: { b: 1 } }, { a: { b: 1 } }) using the lesson's function?

    A shallow comparison uses Object.is on each top-level value. The two inner objects are separate references, so they are not equal. A deep comparison would say true.
  4. 4. Why use an allow-list (pick) instead of a deny-list (omit) for fields a client may update?

    With a deny-list, any field you forget to list is accepted. With an allow-list, only the fields you name get through.

Summary

  • Convert with Object.entries, use array methods, and rebuild with Object.fromEntries to filter, map values or map keys.
  • pick is an allow-list and omit a deny-list; prefer pick for security-sensitive input. Rest destructuring is a quick omit.
  • Inverting an object loses duplicate values and turns keys into strings; group into arrays to keep them all.
  • Computed keys ({ [name]: value }) and fromEntries build objects from variables and arrays.
  • Flatten with dotted paths and unflatten by splitting them; choose a separator your keys never contain.
  • URLSearchParams plus Object.fromEntries parses query strings; values stay strings.
  • === compares identity. Write shallow and deep equality helpers (or use a library) to compare contents.

Next: Number and Math Recipes.