How do you convert a JavaScript Object {} into an Array [] of key-value pairs? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

How do you convert a JavaScript Object {} into an Array [] of key-value pairs?

message-square
0

To convert a plain JavaScript object {} into an array [] of [key, value] pairs without mutating the source object, call Object.entries(obj) after guarding that obj is a non-null plain/record object (not null, a primitive, or an Array). Object.entries(obj) returns a fresh array of two-element [key, value] arrays containing only the object’s own enumerable string-keyed properties—excluding inherited prototype properties and Symbol keys unless handled separately.


1. Converting an Object into [key, value] Pairs with Object.entries()

Validate that the input is a non-null non-array object, optionally filter or transform entries without mutating the source object, and return a new array of [key, value] pairs:

// Convert a plain object into an array of [key, value] pairs without mutating input
function objectToEntries(sourceObj, { includeSymbols = false } = {}) {
  if (typeof sourceObj !== "object" || sourceObj === null || Array.isArray(sourceObj)) {
    throw new TypeError("Expected sourceObj to be a non-null plain/record object.");
  }

  const stringEntries = Object.entries(sourceObj);
  if (!includeSymbols) {
    return stringEntries;
  }

  const symbolEntries = Object.getOwnPropertySymbols(sourceObj)
    .filter((sym) => Object.prototype.propertyIsEnumerable.call(sourceObj, sym))
    .map((sym) => [sym, sourceObj[sym]]);

  return [...stringEntries, ...symbolEntries];
}

// Example usage:
const config = Object.freeze({ host: "localhost", port: 8080, secure: false });
const entries = objectToEntries(config);
console.log(entries); // [["host", "localhost"], ["port", 8080], ["secure", false]]
  • Own enumerable properties only: Ignores properties inherited from Object.prototype and non-enumerable properties.
  • Non-mutating & frozen-safe: Returns a new outer array without altering config or its values.

2. Converting an Object into Custom { key, value } Objects or Filtered Pairs

When a downstream API or UI expects { key, value } objects instead of two-element [key, value] tuples—or needs filtering (null/undefined exclusion)—map over Object.entries() cleanly:

// Transform an object into an array of { key, value } records with optional filtering
function objectToKeyValueRecords(sourceObj, { omitNullish = false } = {}) {
  if (typeof sourceObj !== "object" || sourceObj === null || Array.isArray(sourceObj)) {
    throw new TypeError("Expected sourceObj to be a non-null plain/record object.");
  }

  return Object.entries(sourceObj)
    .filter(([_key, value]) => !omitNullish || (value !== null && value !== undefined))
    .map(([key, value]) => ({ key, value }));
}

// Example usage:
const filters = { q: "async", page: 1, cursor: null };
console.log(objectToKeyValueRecords(filters, { omitNullish: true }));
// [{ key: "q", value: "async" }, { key: "page", value: 1 }]
  • Composable with .filter() and .map(): Object.entries() produces a standard array so array methods chain naturally.
  • Round-trips with Object.fromEntries(): [key, value] pairs can be converted back into an object via Object.fromEntries(entries).

3. Common Traps to Avoid

Converting a JavaScript object into an array of key-value pairs often runs into a few pitfalls:

  • Using for...in without an own-property guard: A raw for (const key in obj) loop walks up the prototype chain and enumerates inherited properties unless guarded by Object.hasOwn(obj, key).
  • Passing null, primitives, or arrays blindly to Object.entries(): Object.entries(null) throws a TypeError, while Object.entries(["a", "b"]) returns [["0", "a"], ["1", "b"]]—validate the input type explicitly first.
  • Assuming Object.entries() includes Symbol keys: Object.entries() only returns string-keyed enumerable properties; Symbol keys require Object.getOwnPropertySymbols() or Reflect.ownKeys().

TL;DR: Guard that the target is a non-null non-array object and call Object.entries(obj) to get a new array of [key, value] pairs of its own enumerable string properties (or .map(([key, value]) => ({ key, value })) if you need { key, value } objects).