JavaScript Object Methods: keys, entries, assign, freeze and More

The global Object has a toolbox of static methods for working with any object: listing its keys, turning it into an array and back, merging objects, freezing configuration so nobody can change it, and controlling individual properties. In this lesson you will learn the methods you will actually use, how to combine them to transform objects (filter, rename, map values), and how to protect shared test configuration from accidental changes.

Advertisement

📖 What You’ll Learn: Object.keys, values and entries, Object.fromEntries, transforming objects with entries, Object.assign versus spread, Object.freeze, seal and preventExtensions and their differences, deep freeze, Object.hasOwn, property descriptors and Object.defineProperty, getOwnPropertyNames, Object.groupBy, and pick and omit helpers for test data.


🔑 Object.keys, Object.values and Object.entries

These three methods turn an object into an array, so all the array methods become available:

📄 keys-values.js

const stock = { pen: 120, notebook: 0, lamp: 7, mug: 0 };

console.log(Object.keys(stock));      // ["pen", "notebook", ...]
console.log(Object.values(stock));    // [120, 0, 7, 0]
console.log(Object.entries(stock));   // [["pen", 120], ...]

const outOfStock = Object.entries(stock).filter(([, qty]) => qty === 0).map(([item]) => item);
console.log("out of stock:", outOfStock);
console.log("total units:", Object.values(stock).reduce((a, b) => a + b, 0));
console.log("product count:", Object.keys(stock).length);

⌨️ Terminal

node keys-values.js

🖥️ Output

[ 'pen', 'notebook', 'lamp', 'mug' ]
[ 120, 0, 7, 0 ]
[ [ 'pen', 120 ], [ 'notebook', 0 ], [ 'lamp', 7 ], [ 'mug', 0 ] ]
out of stock: [ 'notebook', 'mug' ]
total units: 127
product count: 4
  • They return only the object’s own enumerable string keys (no inherited properties, no symbols).
  • Order: integer-like keys in ascending order first, then other string keys in insertion order.
  • ([, qty]) => skips the first element of each entry with destructuring.

🔄 Object.fromEntries: Arrays Back to Objects

Object.fromEntries(entries) is the reverse of Object.entries. It builds an object from [key, value] pairs, from any iterable of pairs, including a Map or URLSearchParams.

📄 from-entries.js

console.log(Object.fromEntries([["env", "qa"], ["workers", 4]]));

const params = new URLSearchParams("q=laptop&page=2&sort=price");
console.log(Object.fromEntries(params));

const headers = new Map([["content-type", "application/json"], ["x-request-id", "abc"]]);
console.log(Object.fromEntries(headers));

⌨️ Terminal

node from-entries.js

🖥️ Output

{ env: 'qa', workers: 4 }
{ q: 'laptop', page: '2', sort: 'price' }
{ 'content-type': 'application/json', 'x-request-id': 'abc' }

The transform pattern: entries → array method → fromEntries

Because objects have no map or filter, convert to entries, transform, and convert back:

📄 transform.js

const prices = { pen: 10, notebook: 45, lamp: 899 };

const withTax = Object.fromEntries(Object.entries(prices).map(([k, v]) => [k, +(v * 1.18).toFixed(2)]));
const expensive = Object.fromEntries(Object.entries(prices).filter(([, v]) => v > 40));
const upperKeys = Object.fromEntries(Object.entries(prices).map(([k, v]) => [k.toUpperCase(), v]));

console.log(withTax);
console.log(expensive);
console.log(upperKeys);

⌨️ Terminal

node transform.js

🖥️ Output

{ pen: 11.8, notebook: 53.1, lamp: 1060.82 }
{ notebook: 45, lamp: 899 }
{ PEN: 10, NOTEBOOK: 45, LAMP: 899 }

Advertisement

🧩 Object.assign vs Spread

Object.assign(target, ...sources) copies properties from the sources into the target and returns the target. It mutates the target. Spread creates a new object instead.

📄 assign.js

const defaults = { browser: "chromium", retries: 0 };
const overrides = { retries: 2 };

const merged1 = Object.assign({}, defaults, overrides);   // safe: empty target
const merged2 = { ...defaults, ...overrides };             // same result
console.log(merged1, merged2);

Object.assign(defaults, overrides);                        // mutates defaults!
console.log(defaults);

⌨️ Terminal

node assign.js

🖥️ Output

{ browser: 'chromium', retries: 2 } { browser: 'chromium', retries: 2 }
{ browser: 'chromium', retries: 2 }

💡 Tip: Prefer spread for merging into a new object. Use Object.assign(this, options) when you deliberately want to copy options onto an existing object, for example in a class constructor.


🧊 freeze, seal and preventExtensions

Three levels of protection for an object:

MethodAdd propertiesDelete propertiesChange values
Object.preventExtensions(o)NoYesYes
Object.seal(o)NoNoYes
Object.freeze(o)NoNoNo

📄 freeze.js

"use strict";

const sealed = Object.seal({ env: "qa" });
sealed.env = "staging";                  // allowed
try { sealed.newKey = 1; } catch (e) { console.log("seal:", e.message); }

const frozen = Object.freeze({ env: "qa" });
try { frozen.env = "prod"; } catch (e) { console.log("freeze:", e.message); }
console.log(sealed.env, frozen.env, Object.isFrozen(frozen), Object.isSealed(sealed));

⌨️ Terminal

node freeze.js

🖥️ Output

seal: Cannot add property newKey, object is not extensible
freeze: Cannot assign to read only property 'env' of object '#<Object>'
staging qa true true

In strict mode (ES modules, classes, "use strict") a forbidden change throws a TypeError. In sloppy mode it is silently ignored, which hides bugs.

freeze is shallow

📄 deep-freeze.js

const config = Object.freeze({ env: "qa", urls: { api: "https://api.qa" } });
config.urls.api = "https://evil.example";   // nested object is NOT frozen
console.log(config.urls.api);

function deepFreeze(obj) {
  for (const value of Object.values(obj)) {
    if (value && typeof value === "object") deepFreeze(value);
  }
  return Object.freeze(obj);
}
const safe = deepFreeze({ env: "qa", urls: { api: "https://api.qa" } });
safe.urls.api = "https://evil.example";
console.log(safe.urls.api, Object.isFrozen(safe.urls));

⌨️ Terminal

node deep-freeze.js

🖥️ Output

https://evil.example
https://api.qa true

💡 Tip: Deep-freeze shared test configuration and base test data. Any test that tries to change them then fails immediately in strict code, instead of silently affecting other tests.


✅ Object.hasOwn and Property Checks

📄 hasown.js

const response = { id: 1, error: undefined };

console.log(Object.hasOwn(response, "error"));      // exists, even though undefined
console.log(Object.hasOwn(response, "toString"));   // inherited: false
console.log("toString" in response);                 // in sees inherited

const dict = Object.create(null);                    // object without a prototype
dict.key = "value";
console.log(Object.hasOwn(dict, "key"), typeof dict.hasOwnProperty);

⌨️ Terminal

node hasown.js

🖥️ Output

true
false
true
true undefined

Object.hasOwn (ES2022) replaces the older obj.hasOwnProperty(key), which fails on objects created with Object.create(null) because they have no hasOwnProperty method.


Advertisement

🔬 Property Descriptors and Object.defineProperty

Definition: every property has a hidden descriptor with flags: writable (can the value change?), enumerable (does it show up in Object.keys and loops?) and configurable (can it be deleted or redefined?). Normal assignments create properties with all three set to true.

📄 descriptors.js

const user = { name: "Asha" };
console.log(Object.getOwnPropertyDescriptor(user, "name"));

Object.defineProperty(user, "id", { value: 7, writable: false, enumerable: false });
Object.defineProperty(user, "password", { value: "secret", enumerable: false });

user.id = 99;                               // ignored: not writable
console.log(user.id);
console.log(Object.keys(user));             // hidden properties are not listed
console.log(JSON.stringify(user));          // and not serialised
console.log(Object.getOwnPropertyNames(user));   // but they exist

⌨️ Terminal

node descriptors.js

🖥️ Output

{ value: 'Asha', writable: true, enumerable: true, configurable: true }
7
[ 'name' ]
{"name":"Asha"}
[ 'name', 'id', 'password' ]

You will rarely call defineProperty yourself, but it explains why some properties do not show up in logs or JSON, and how frameworks create read-only and computed properties. Getters and setters are covered in Module 8.


🗂️ Object.groupBy

Object.groupBy(items, callback) (ES2024) groups the items of an array (or any iterable) into an object whose keys are the callback’s return values:

📄 groupby.js

const tests = [
  { name: "login", status: "passed", browser: "chromium" },
  { name: "search", status: "failed", browser: "firefox" },
  { name: "cart", status: "passed", browser: "firefox" },
];

const byStatus = Object.groupBy(tests, (t) => t.status);
console.log(Object.fromEntries(Object.entries(byStatus).map(([k, v]) => [k, v.map((t) => t.name)])));

const byBrowser = Object.groupBy(tests, ({ browser }) => browser);
console.log(Object.keys(byBrowser), byBrowser.firefox.length);

⌨️ Terminal

node groupby.js

🖥️ Output

{ passed: [ 'login', 'cart' ], failed: [ 'search' ] }
[ 'chromium', 'firefox' ] 2

🧪 Tester Scenario: pick, omit and Compare Configurations

Small helpers built from the methods in this lesson cover many everyday test tasks: choosing fields to assert, removing secrets before logging, and showing what differs between two environments.

📄 pick-omit.js

const pick = (obj, keys) => Object.fromEntries(Object.entries(obj).filter(([k]) => keys.includes(k)));
const omit = (obj, keys) => Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k)));

const user = { id: 7, name: "Asha", email: "asha@sqatools.in", password: "Secret@1", token: "eyJhbGci..." };
console.log("assert on:", pick(user, ["id", "email"]));
console.log("safe to log:", omit(user, ["password", "token"]));

function diffConfig(a, b) {
  const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
  return [...keys]
    .filter((k) => !Object.is(a[k], b[k]))
    .map((k) => `${k}: ${JSON.stringify(a[k])} -> ${JSON.stringify(b[k])}`);
}

const qa = { baseURL: "https://qa.example.com", retries: 1, workers: 4, video: "off" };
const prod = { baseURL: "https://www.example.com", retries: 2, workers: 4, trace: "on" };
console.log(diffConfig(qa, prod));

⌨️ Terminal

node pick-omit.js

🖥️ Output

assert on: { id: 7, email: 'asha@sqatools.in' }
safe to log: { id: 7, name: 'Asha', email: 'asha@sqatools.in' }
[
  'baseURL: "https://qa.example.com" -> "https://www.example.com"',
  'retries: 1 -> 2',
  'video: "off" -> undefined',
  'trace: undefined -> "on"'
]

Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Print how many keys { a: 1, b: 2, c: 3, d: 4 } has and the sum of its values.

Show answer

📄 practice1.js

const obj = { a: 1, b: 2, c: 3, d: 4 };
console.log(Object.keys(obj).length, Object.values(obj).reduce((s, v) => s + v, 0));

🖥️ Output

4 10

Q2. Swap keys and values: turn { chromium: "Blink", firefox: "Gecko" } into { Blink: "chromium", Gecko: "firefox" }.

Show answer

📄 practice2.js

const engines = { chromium: "Blink", firefox: "Gecko" };
console.log(Object.fromEntries(Object.entries(engines).map(([k, v]) => [v, k])));

🖥️ Output

{ Blink: 'chromium', Gecko: 'firefox' }

Q3. Remove every property whose value is null or undefined from { a: 1, b: null, c: "x", d: undefined, e: 0 }.

Show answer

📄 practice3.js

const obj = { a: 1, b: null, c: "x", d: undefined, e: 0 };
console.log(Object.fromEntries(Object.entries(obj).filter(([, v]) => v != null)));

🖥️ Output

{ a: 1, c: 'x', e: 0 }

Q4. Freeze a config object and show (in strict mode) that changing it throws.

Show answer

📄 practice4.js

"use strict";
const config = Object.freeze({ timeout: 30000 });
try {
  config.timeout = 1;
} catch (e) {
  console.log(e.constructor.name, "-", e.message);
}
console.log(config.timeout);

🖥️ Output

TypeError - Cannot assign to read only property 'timeout' of object '#<Object>'
30000

Q5. Convert the query string "?env=qa&debug=true&workers=2" into an object, then convert workers to a number and debug to a boolean.

Show answer

📄 practice5.js

const raw = Object.fromEntries(new URLSearchParams("?env=qa&debug=true&workers=2"));
const parsed = { ...raw, debug: raw.debug === "true", workers: Number(raw.workers) };
console.log(raw, parsed);

🖥️ Output

{ env: 'qa', debug: 'true', workers: '2' } { env: 'qa', debug: true, workers: 2 }

Q6. Write renameKeys(obj, map) that renames keys using a mapping such as { fname: "firstName" }, keeping other keys as they are.

Show answer

📄 practice6.js

const renameKeys = (obj, map) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [map[k] ?? k, v]));
console.log(renameKeys({ fname: "Asha", lname: "Rao", age: 29 }, { fname: "firstName", lname: "lastName" }));

🖥️ Output

{ firstName: 'Asha', lastName: 'Rao', age: 29 }

🧠 MCQ Quiz: Object Methods

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does Object.keys({ x: 1, y: 2 }) return?
  2. Which method builds an object from [key, value] pairs?
  3. What does Object.assign(target, source) return?
  4. After Object.seal(o), what is still allowed?
  5. Does Object.freeze freeze nested objects?
  6. In sloppy mode, what happens when you assign to a frozen property?
  7. Why prefer Object.hasOwn over obj.hasOwnProperty?
  8. A property defined with enumerable: false…
  9. What does Object.groupBy([1, 2, 3, 4], (n) => n % 2 ? "odd" : "even") produce?
  10. How do you “map” over an object’s values?

💼 Interview Questions and Answers

Q1. What is the difference between Object.freeze and Object.seal?

Both prevent adding and deleting properties. seal still allows changing the values of existing properties; freeze also makes every existing property read-only. Both are shallow: nested objects remain mutable unless frozen too. Violations throw in strict mode and are silently ignored otherwise.

Q2. How do you deep clone and deep freeze an object?

Deep clone: structuredClone(obj) (handles nested objects, arrays, dates, Maps and Sets; not functions or class prototypes). Deep freeze: a recursive function that calls Object.freeze on every nested object, as shown in this lesson. Libraries such as Immer provide immutable updates at scale.

Q3. How do you iterate over an object and transform it?

Use Object.entries(obj) to get [key, value] pairs, transform them with array methods (map, filter), and rebuild with Object.fromEntries. For example, removing null values: Object.fromEntries(Object.entries(obj).filter(([, v]) => v != null)).

Q4. Why might a property be missing from console output or JSON even though you can read it?

It may be non-enumerable (defined with enumerable: false), a getter on the prototype (class getters are not own properties), or a symbol key. Object.keys, for...in and JSON.stringify skip them. Object.getOwnPropertyNames, Object.getOwnPropertySymbols and Reflect.ownKeys list them.

📄 getter.js

class Point {
  constructor(x) { this.x = x; }
  get double() { return this.x * 2; }
}
const p = new Point(4);
console.log(p.double, Object.keys(p), JSON.stringify(p));

⌨️ Terminal

node getter.js

🖥️ Output

8 [ 'x' ] {"x":4}

Advertisement

❓ Frequently Asked Questions

🤔 What is the difference between Object.keys and for…in?

Object.keys returns only the object’s own enumerable keys as an array. for...in also visits inherited enumerable keys.

🤔 How do I merge two objects?

Use spread: { ...a, ...b } (b wins on conflicts). For nested objects, merge each level you care about, or use a deep-merge utility.

🤔 How do I make an object immutable?

Use Object.freeze for one level, and a recursive deep freeze for nested data. In strict mode, attempts to change it throw errors.

🤔 Is Object.groupBy available everywhere?

It is part of ES2024 and works in Node.js 21+ and current browsers. For older environments, use reduce.


🏁 Summary

  • Object.keys, values and entries turn objects into arrays; Object.fromEntries turns pairs back into objects.
  • Transform objects with the entries → map/filter → fromEntries pattern.
  • Object.assign mutates its target; spread creates a new object.
  • preventExtensions < seal < freeze in strictness, and all are shallow.
  • Descriptors control whether properties are writable, enumerable and configurable; Object.hasOwn checks own properties safely.

Next, continue with Lesson 35: JSON and Deep Copy.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in