TechEarl

JavaScript Object Methods: keys, values, entries, fromEntries, and freeze

The object methods I reach for daily: Object.keys/values/entries, the entries to fromEntries round-trip, destructuring objects and arrays, Object.hasOwn as the modern hasOwnProperty, why Object.freeze is only shallow, and merging and deep-cloning objects with spread, Object.assign and structuredClone.

Ishan KarunaratnePublished ⏱️ 18 min readUpdated
Share thisCopied
JavaScript object methods: keys, values, entries, fromEntries, hasOwn and freeze, plus destructuring, spread merges, and deep cloning with structuredClone.

The JavaScript object methods that matter day to day are Object.keys, Object.values and Object.entries (read an object as arrays), Object.fromEntries (build one back), Object.hasOwn (check an own key) and Object.freeze (lock it, one level deep). This page covers those, plus destructuring, merging and deep-cloning objects, and when a Map is the better container.

Arrays have a rich set of iteration methods; plain objects do not. You cannot call .map() or .filter() on a {}. The trick I use constantly is to bridge the two worlds: turn the object into an array of [key, value] pairs with Object.entries, do array work on it, then turn the result back into an object with Object.fromEntries. That round-trip is the single most useful object idiom in modern JavaScript, so it comes first.

The three iterators: keys, values, entries

All three take an object and hand you back an array, so you can iterate with for...of, .forEach, or any array method:

javascript
const prices = { coffee: 3, tea: 2, juice: 4 };

Object.keys(prices);    // ["coffee", "tea", "juice"]
Object.values(prices);  // [3, 2, 4]
Object.entries(prices); // [["coffee", 3], ["tea", 2], ["juice", 4]]

Object.entries is the one I use most, because each pair destructures cleanly in a loop:

javascript
for (const [name, price] of Object.entries(prices)) {
  console.log(`${name}: $${price}`);
}

These only see an object's own, enumerable, string-keyed properties, which is almost always what you want. That is the key difference from the old for...in loop, which also walks inherited properties up the prototype chain and is why for...in code is littered with hasOwnProperty guards. With Object.keys and friends, you do not need the guard at all.

The round-trip: entries to fromEntries

Object.fromEntries is the inverse of Object.entries: give it an array of [key, value] pairs and it builds an object. Put the two together and you can map and filter over an object as if it were an array, then come back to object shape.

Filter an object down to the entries you want:

javascript
const inventory = { apples: 5, bananas: 0, cherries: 12, dates: 0 };

// Keep only the items still in stock
const inStock = Object.fromEntries(
  Object.entries(inventory).filter(([, qty]) => qty > 0)
);
// { apples: 5, cherries: 12 }

Transform the values:

javascript
// Apply a 10% markup to every price
const marked = Object.fromEntries(
  Object.entries(prices).map(([name, price]) => [name, price * 1.1])
);

Once you internalize this pattern, a lot of awkward object code disappears. A small helper makes it read even better, and the te prefix keeps it from colliding with anything:

javascript
// Map over an object's values, keep its keys
function teMapValues(obj, fn) {
  return Object.fromEntries(
    Object.entries(obj).map(([key, value]) => [key, fn(value, key)])
  );
}

teMapValues(prices, (p) => p * 1.1);

Object.fromEntries also takes anything that yields pairs, including a Map, so it is the clean way back from a Map to a plain object: Object.fromEntries(myMap). The reverse, new Map(Object.entries(obj)), gets you from object to Map. If you are building an object out of two parallel arrays or parsing structured input, the entries form is usually the most direct route. (Object.fromEntries landed in ES2019 and is in every current runtime.)

A close cousin of this work is reading values out of an object into variables, which is what JavaScript destructuring (next section) is for, and the array side of these iterators lines up with the JavaScript array methods you would chain after Object.entries.

JavaScript destructuring

Destructuring pulls values out of an object or array and binds them to variables in one statement, instead of reading them one property at a time. Object patterns use braces and match by key name; array patterns use brackets and match by position:

javascript
const user = { name: "Ada", role: "admin" };
const { name, role } = user;          // name = "Ada", role = "admin"

const point = [10, 20];
const [x, y] = point;                 // x = 10, y = 20

The braces on the left are not an object literal; they are a pattern that says "find these keys and bind them." Order does not matter in an object pattern, and a key that does not exist yields undefined, not an error. Destructuring has been stable since ES2015 (ES6) and the syntax has not changed since, so everything below works in every current browser and in Node.

Skipping elements and swapping variables

In an array pattern the variable names are yours to choose. Leave a hole to skip a position (the commas still count), and use a pattern on both sides to swap two variables with no temporary:

javascript
const parts = ["2026", "06", "01"];
const [, , day] = parts;              // day = "01"

let a = 1, b = 2;
[a, b] = [b, a];                      // a = 2, b = 1

The rest pattern

A trailing ...rest gathers everything you did not name. With arrays it collects the remaining elements into a new array; with objects it collects the remaining own enumerable properties into a new object:

javascript
const [first, ...others] = [1, 2, 3, 4];
// first = 1, others = [2, 3, 4]

const { id, ...fields } = { id: 7, name: "Ada", role: "admin" };
// id = 7, fields = { name: "Ada", role: "admin" }

The object-rest form is the idiomatic way to grab one property and keep "everything else" as a clean object, for example to strip an id before sending a payload. The rest element must come last; putting anything after it is a syntax error.

Aliases and default values

When the property key is not the variable name you want, rename it with key: localName. Read the colon as "bind this key to this variable": after the line below, user_id is not in scope, only userId is. That is the single most common point of confusion.

javascript
const response = { user_id: 42, created_at: "2026-06-01" };
const { user_id: userId, created_at: createdAt } = response;
// userId = 42, createdAt = "2026-06-01"

Give any target a default with =. The default is used only when the value is undefined (a missing key or a missing array slot); a present null, 0, or "" is kept as is. Alias and default combine in the order key: localName = default:

javascript
const { timeout = 5000, retries = 3 } = { timeout: 1000 };
// timeout = 1000 (present, kept), retries = 3 (missing, defaulted)

const [primary = "main", secondary = "backup"] = ["db1"];
// primary = "db1", secondary = "backup"

const { color: themeColor = "blue" } = {};
// themeColor = "blue"

Nested destructuring and the path gotcha

Patterns nest the same way the data does. To reach a value two levels deep, mirror the shape:

javascript
const order = { customer: { address: { city: "Berlin" } } };
const { customer: { address: { city } } } = order;
// city = "Berlin"

The gotcha: in that pattern, customer and address are not variables. They are path segments telling the engine where to walk, and the only binding created is city. If you want a customer variable too, name it separately:

javascript
const { customer, customer: { address: { city } } } = order;
// now both `customer` (the object) and `city` (the string) exist

The nested form is also a footgun when an intermediate level can be missing: const { a: { b } } = {} throws TypeError: Cannot destructure property 'b' of 'undefined', because there is no a to read b from. Default the intermediate level (const { a: { b } = {} } = obj) or read it with optional chaining (covered in reading nested values safely below) when the shape is not guaranteed.

Destructuring function arguments (the = {} gotcha)

Destructuring an options object right in the parameter list self-documents which options a function accepts and pairs naturally with defaults:

javascript
function te_connect({ host = "localhost", port = 5432, ssl = false }) {
  return `${host}:${port}${ssl ? " (ssl)" : ""}`;
}

te_connect({ port: 6432 });      // "localhost:6432"

That works as long as the caller passes an object. Call it with nothing, te_connect(), and it throws: you cannot destructure undefined. The fix is to default the whole parameter to an empty object so there is always something to destructure:

javascript
function te_connect({ host = "localhost", port = 5432, ssl = false } = {}) {
  return `${host}:${port}${ssl ? " (ssl)" : ""}`;
}

te_connect();                    // "localhost:5432", no throw

The trailing = {} is not optional decoration. Make it a reflex on any function that destructures its parameter, because the call site that omits the argument is exactly the one you forget to test. A related guideline I keep: once a function needs more than about three arguments, switch from positional parameters to a single destructured options object. It reads better at the call site (named, order-independent) and grows without breaking existing callers.

The same patterns work in loops. for...of over Object.entries(...) (shown above), an array of pairs, or a Map yields [key, value] pairs that destructure directly, and array callbacks do it inline with arr.map(([k, v]) => ...):

javascript
const settings = new Map([["theme", "dark"], ["lang", "en"]]);
for (const [key, value] of settings) {
  console.log(key, value);
}

Object.hasOwn: the modern hasOwnProperty

When you do need to ask "does this object have this key as its own property," the old answer was obj.hasOwnProperty(key). The problem: hasOwnProperty lives on the prototype, so it breaks the moment the object does not inherit from Object.prototype (more on that below), or when the object itself has a property literally named hasOwnProperty. The defensive workaround people wrote for years was ugly:

javascript
// The old guard you no longer need
Object.prototype.hasOwnProperty.call(obj, key);

Object.hasOwn(obj, key) replaces all of that. It is a static method, so it never depends on the object's prototype:

javascript
const settings = { darkMode: true };

Object.hasOwn(settings, "darkMode"); // true
Object.hasOwn(settings, "toString"); // false (inherited, not own)

Object.hasOwn reached Baseline in 2022 (it is part of ES2022) and shipped in Node.js 16.9.0, so on any current Node or browser it is the default I reach for. The null-prototype objects in the next section are exactly the case that makes the old obj.hasOwnProperty(key) blow up, and the precise reason Object.hasOwn exists.

Object.freeze is shallow (this trips everyone up)

Object.freeze(obj) makes an object's own properties non-writable and non-configurable: you cannot reassign them, add new ones, or delete existing ones. It is how I lock down a constants object. But the gotcha that bites people is that the freeze is shallow. It applies only to the immediate properties. Any nested object stays fully mutable:

javascript
const config = Object.freeze({
  name: "prod",
  limits: { maxUsers: 100 },
});

config.name = "dev";        // silently ignored (throws in strict mode)
config.limits.maxUsers = 5; // works. limits is a different object, not frozen

That second line is the trap. config is frozen, but config.limits points at a separate object that freeze never touched. If you want true immutability all the way down, you have to recurse. Here is the deep-freeze helper I keep around:

javascript
function teDeepFreeze(obj) {
  // Freeze the object first, then recurse. A cyclic reference (a child that
  // points back at an ancestor) then lands on an already-frozen object and
  // the isFrozen check stops it, instead of looping forever.
  Object.freeze(obj);
  for (const value of Object.values(obj)) {
    if (value && typeof value === "object" && !Object.isFrozen(value)) {
      teDeepFreeze(value);
    }
  }
  return obj;
}

The order matters: freeze first, recurse second. If you recurse before freezing, a cyclic reference never sees a frozen object and the Object.isFrozen(value) guard cannot fire, so the function loops forever. Freezing the current object up front means a cycle reaches an already-frozen node and the guard short-circuits it. Object.isFrozen(obj) is also how you ask after the fact whether an object is locked.

There is a lighter-weight sibling, Object.seal, which prevents adding or deleting properties but still lets you change the values of existing ones. It is the right tool when you want a fixed shape but mutable contents. Object.freeze is Object.seal plus making the existing values read-only too. Both are shallow, so the same nested-object caveat applies to Object.seal.

If your goal is producing a new merged object rather than locking one down, the next section covers Object.assign and spread, including the same shallow-vs-deep distinction in a copy context.

Merge objects in JavaScript

To merge two objects, spread them both into a new object literal: const merged = {...a, ...b}. Object.assign({}, a, b) does the same thing. Both copy each source's own enumerable properties onto a target, left to right, so a key in b overwrites the same key in a:

javascript
const defaults = { theme: "light", retries: 3 };
const overrides = { retries: 5 };

const config = { ...defaults, ...overrides };
// { theme: "light", retries: 5 }

// Object.assign mutates its first argument, so pass a fresh {} target:
const same = Object.assign({}, defaults, overrides);
// { theme: "light", retries: 5 }

Spread reads cleaner and is what I reach for. Object.assign earns its place when you genuinely want to mutate an existing object in place (Object.assign(target, patch)), since spread always builds a new object. Spread syntax has been Baseline since 2018 and Object.assign since 2015, so both are safe everywhere. That is the easy part; three behaviors account for almost every "my merge did something weird" bug.

Spread merge gotchas: shallow, last wins, undefined overwrites

The merge is shallow, one level deep. Spread and Object.assign copy top-level keys by reference. Nested objects are not merged; the whole nested value from the right replaces the one on the left:

javascript
const a = { user: { name: "Sam", role: "admin" } };
const b = { user: { name: "Riley" } };

const merged = { ...a, ...b };
// { user: { name: "Riley" } }
// role is GONE: b.user replaced a.user wholesale, it was not deep-merged

Because nested objects are copied by reference, merged.user is the very same object as b.user, so mutating one mutates the other (any nested object that came only from a would be shared with a the same way). That is the same shallow trap as Object.freeze above, in a copy context. A deep merge or a real clone fixes it.

The last (right-most) value wins. That is the whole point of an overrides pattern, but people who write { ...overrides, ...defaults } then wonder why their defaults clobbered the user's choices. Put the object whose values should take priority on the right:

javascript
const merged = { ...{ size: "M" }, ...{ size: "L" }, ...{ size: "S" } };
// { size: "S" }, last spread wins

undefined overwrites, it does not skip. An explicit undefined in a later object overwrites an earlier real value. This bites when an options object is built from something like { timeout: userInput.timeout } and the input happens to be undefined:

javascript
const defaults = { timeout: 5000 };
const opts = { timeout: undefined };

const merged = { ...defaults, ...opts };
// { timeout: undefined }, NOT 5000

The entries round-trip from earlier makes a small helper to drop undefined values before merging:

javascript
const teDefined = (obj) =>
  Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));

const merged = { ...defaults, ...teDefined(opts) };
// { timeout: 5000 }: the undefined was stripped, the default survives

null is a real value and is not stripped here, only undefined is. That is usually what you want, but decide deliberately.

Deep-clone with structuredClone

When you need an independent copy rather than a merge, the native answer is structuredClone(obj). It recursively clones the whole structure, so mutating the copy never touches the original:

javascript
const original = { user: { name: "Sam" }, tags: new Set(["a", "b"]), when: new Date() };

const copy = structuredClone(original);
copy.user.name = "Riley";

original.user.name; // "Sam", untouched, fully independent

structuredClone is global in browsers (Chrome 98, Firefox 94, Safari 15.4, all since early 2022) and in Node.js since version 17. It replaces the old JSON.parse(JSON.stringify(obj)) trick and is strictly better: it preserves Date objects (JSON turns them into strings), Map and Set, ArrayBuffer, and typed arrays, and it handles cyclic references without blowing the stack.

What it cannot clone matters just as much. It throws a DataCloneError (a DOMException) if any part of the value is a function or a DOM node. It does not throw on a class instance, but it does not preserve it either: own enumerable properties are copied, the prototype and its methods are dropped, so a User instance comes back as a plain object. (Error, Date, Map, Set, RegExp, and typed arrays clone fine.) It is perfect for plain data, config trees and API responses, and wrong for anything carrying behavior.

javascript
structuredClone({ run: () => {} });
// DataCloneError: () => {} could not be cloned.

If you only need a one-level copy and accept shared references, { ...obj } is faster and fine.

Deep-merge: there is no native one

JavaScript has no built-in deep merge. structuredClone clones, spread merges shallowly, and nothing in the standard library recursively merges two objects. Here is the compact recursive merger I use: where both sides hold a plain object at the same key, it merges them rather than letting the right side replace the left:

javascript
// Plain means a {} literal or Object.create(null), not a Date, Map, array or class instance
const teIsPlainObject = (v) => {
  if (v === null || typeof v !== "object") return false;
  const proto = Object.getPrototypeOf(v);
  return proto === Object.prototype || proto === null;
};

function teDeepMerge(target, source) {
  const out = { ...target };
  for (const key of Object.keys(source)) {
    if (key === "__proto__") continue; // never merge a prototype key from untrusted JSON
    if (teIsPlainObject(out[key]) && teIsPlainObject(source[key])) {
      out[key] = teDeepMerge(out[key], source[key]);
    } else {
      out[key] = source[key];
    }
  }
  return out;
}

const a = { user: { name: "Sam", role: "admin" } };
const b = { user: { name: "Riley" } };

teDeepMerge(a, b);
// { user: { name: "Riley", role: "admin" } }, role survives

It deliberately keeps the scope small: it deep-merges plain objects, replaces everything else (a Date, Map or class instance on the right replaces the left value as-is rather than being recursed into, and arrays are replaced too, since merging two arrays is its own question), and copies the top level rather than mutating target. For truly independent output, wrap the result in structuredClone, or clone the inputs first. It does not guard against cyclic references, so do not point it at the DOM or a circular graph.

If you want a battle-tested version with array-handling options and cycle safety, lodash's merge (import merge from "lodash/merge") is the standard library choice; lodash.merge mutates its destination while lodash.mergeWith lets you customize how each key combines. For config and API-shape merging, the twenty lines above are usually all I need, and one fewer dependency is one fewer thing to keep current.

Reading nested values safely

Half the reason people deep-merge is to safely read a value that may or may not be there. Optional chaining (?.) handles that read without any merge at all, short-circuiting to undefined the moment a link in the chain is missing instead of throwing "cannot read properties of undefined":

javascript
const res = { data: { user: { profile: null } } };

res.data?.user?.profile?.avatar;      // undefined, no throw
res.data?.user?.profile?.avatar ?? "default.png";  // "default.png"

Pair it with the nullish coalescing operator (??) to supply a fallback only when the value is null or undefined, not when it is 0 or an empty string (which || would wrongly replace). Optional chaining and ?? have both been Baseline since 2020, and together they retire the hand-rolled "split on dots and walk the object" utilities that used to fill this gap.

Object.create(null) versus a Map

A plain {} inherits from Object.prototype, which means it carries inherited keys like toString, constructor, and hasOwnProperty. When you use an object as a lookup table built from external data, that inheritance is a liability: a key named "constructor" collides with something real, and "hasOwnProperty" in the data shadows the method you might call. Object.create(null) makes a "null-prototype" object with no inherited anything, a clean dictionary:

javascript
const dict = Object.create(null);
dict.constructor = "totally fine now";

// But it has no inherited methods at all:
dict.hasOwnProperty;        // undefined
Object.hasOwn(dict, "foo"); // use this instead, it is static

This is a real-world footgun. I have been bitten by a library (an older query-string parser) returning Object.create(null): my code called .hasOwnProperty() on the result and threw, because the method was not there. Object.hasOwn sidesteps it entirely, which is the connection to the section above. Parsing URL parameters is exactly that kind of data, see parsing query string parameters for the dictionary-shaped result that benefits from this.

So when do you use a null-prototype object versus a real Map? My rule:

  • Null-prototype object when keys are strings, the shape is roughly static, and you want a plain JSON-serializable object at the end (a config blob, a parsed-params bag). It serializes with JSON.stringify for free; a Map does not.
  • Map when keys can be non-strings (objects, numbers that must stay numbers), or when you add and delete entries frequently and want .has, .get, .set, .delete, and a reliable .size. Map preserves insertion order and is built for churn.

For a string-keyed thing you read more than you write, the object is simpler. For arbitrary keys or heavy mutation, reach for Map.

All three return an array built from an object's own enumerable string-keyed properties. Object.keys returns the keys, Object.values returns the values, and Object.entries returns an array of [key, value] pairs. Use Object.entries when you want both at once, since each pair destructures cleanly in a loop.

Use Object.fromEntries, the inverse of Object.entries. Pass it any iterable of [key, value] pairs, including a Map, and it builds a plain object. Pairing Object.entries with Object.fromEntries lets you map and filter over an object as if it were an array, then return to object shape.

Object.hasOwn(obj, key) is the modern replacement. It is a static method that does not depend on the object's prototype, so it works on null-prototype objects and is not broken by a property literally named hasOwnProperty. It reached Baseline in 2022 and shipped in Node.js 16.9.0, so it is safe on any current runtime.

Because Object.freeze is shallow. It only locks the immediate properties of the object you pass it. A nested object is a separate object that freeze never touched, so it stays mutable. To lock everything, recurse with a deep-freeze helper that walks Object.values and freezes each nested object.

Use the alias form const { key: newName } = obj. After that, only newName is in scope, not key. To rename and supply a default at once, write { key: newName = defaultValue }.

Because destructuring undefined throws a TypeError. When you write function f({ a } = {}) and call f(), the argument is undefined, so the = {} default kicks in and gives the pattern an empty object to destructure. Drop the = {} and f() crashes with "Cannot destructure property of undefined."

Only when the value is undefined, which means a missing object key or a missing array slot. A present value of null, 0, false, or "" is kept, because the default triggers on undefined alone, not on any falsy value.

They produce the same shallow merge. The difference is mutation: {...a, ...b} always creates a new object, while Object.assign(target, source) mutates and returns target. Pass a fresh {} as the first argument to Object.assign when you do not want to mutate an input. Spread is the more common, more readable choice in modern code.

No. structuredClone deep-clones a single object into an independent copy, it does not combine two objects. Clone first if you want independence, then deep-merge, or deep-merge and clone the result. They solve different problems.

A spread copies every own key, including ones whose value is undefined, so {...defaults, ...{x: undefined}} sets x to undefined rather than keeping the default. Strip undefined values before merging (filter Object.entries and rebuild with Object.fromEntries) or read each value defensively with optional chaining and ??.

Use a Map when keys can be non-strings (objects or numbers that must stay numbers), or when you add and delete entries frequently and want .has, .delete, and a reliable .size. Use a plain object (or a null-prototype object via Object.create(null)) when keys are strings, the shape is roughly static, and you want a JSON-serializable result.

See also

Sources

Authoritative references this article was fact-checked against.

TagsjavascriptObject.entriesObject.fromEntriesObject.keysObject.freezeObject.hasOwndestructuringspread operatorstructuredClonedeep merge

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

JavaScript array methods in 2026: at, flat, toSorted, toSpliced, merge, insert, dedupe with Set, a Fisher-Yates shuffle, reduce, and Object.groupBy.

Modern JavaScript Array Methods: at, flat, toReversed, and groupBy

The JavaScript array methods worth reaching for in 2026, with the tasks they solve: convert and fill arrays, at() and flat(), merge, insert at an index, the copying toReversed/toSorted/toSpliced/with, dedupe with Set, random picks and a correct shuffle, reduce, and Object.groupBy (not the Array.prototype.group that never shipped).

How JavaScript promises work: states, async/await, Promise.all vs allSettled vs race vs any, concurrency limits, polling, debounce and throttle, and mistakes.

JavaScript Promises Explained: A Complete Guide

How JavaScript promises actually work: the three states, .then/.catch/.finally, async/await, Promise.all vs allSettled vs race vs any, limiting concurrency with a promise pool, sleep and polling, debounce and throttle, what async functions desugar to, and the promise mistakes that bite in production.