How do you iterate over an array of objects and access each object's properties in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you iterate over an array of objects and access each object's properties in JavaScript?

message-square
0

To iterate over an array of objects and access each object’s properties in JavaScript, validate that the input is an Array (Array.isArray(items)) and each element is a non-null plain/record object (typeof item === "object" && item !== null && !Array.isArray(item)), iterate with a for...of or index for loop (or .forEach() / .map() when transforming), access properties safely via Object.prototype.hasOwnProperty.call(item, key) or destructuring with defaults, and wrap iteration and property extraction inside a try / catch block—using a Map when indexing or aggregating extracted properties so dynamic keys never collide with Object.prototype properties.


1. Iterating Over an Array of Objects and Reading Properties Safely with try / catch

Validate the outer array and each object element with typeof / Array.isArray guards, read own properties safely, and wrap execution inside try / catch:

// Iterate over an array of objects and extract formatted property summaries safely
function extractObjectSummaries(records, requiredKeys = ["id", "name"]) {
  if (!Array.isArray(records)) {
    throw new TypeError("Expected records to be an Array instance.");
  }
  if (!Array.isArray(requiredKeys)) {
    throw new TypeError("Expected requiredKeys to be an Array instance.");
  }

  try {
    const normalizedKeys = [];
    for (let k = 0; k < requiredKeys.length; k += 1) {
      const keyName = requiredKeys[k];
      if (typeof keyName !== "string" || keyName.trim().length === 0) {
        throw new TypeError(`Expected required key at index ${k} to be a non-empty string.`);
      }
      normalizedKeys.push(keyName.trim());
    }

    const summaries = [];

    for (let i = 0; i < records.length; i += 1) {
      const item = records[i];
      if (typeof item !== "object" || item === null || Array.isArray(item)) {
        throw new TypeError(`Expected item at index ${i} to be a non-null plain/record object.`);
      }

      const rowMap = new Map();
      for (let j = 0; j < normalizedKeys.length; j += 1) {
        const propKey = normalizedKeys[j];
        const hasOwnProp = Object.prototype.hasOwnProperty.call(item, propKey);
        const propValue = hasOwnProp ? item[propKey] : null;
        rowMap.set(propKey, propValue);
      }

      summaries.push(rowMap);
    }

    return summaries;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed iterating over objects array: ${message}`);
  }
}

// Example usage:
// try {
//   const users = [
//     { id: 101, name: "Amina Tariq", role: "engineer" },
//     { id: 102, name: "Bilal Raza", role: "maintainer" }
//   ];
//   const rows = extractObjectSummaries(users, ["id", "name", "role"]);
//   console.log("First user name:", rows[0].get("name")); // "Amina Tariq"
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Prefer for...of or index for loops when you need break, continue, or async/await flow control: .forEach() cannot be broken out of early with break and does not await async callbacks sequentially.
  • Check Object.prototype.hasOwnProperty.call(obj, key) before reading dynamic keys: Ensures you read own properties rather than inherited prototype properties.

2. Indexing or Aggregating Object Properties into a Map

When looking up objects by a dynamic property value (such as id or code) or grouping properties across an array of objects, store entries in a Map inside try / catch so keys never collide with Object.prototype properties:

// Index an array of objects by a chosen key property into a Map with validation and try / catch
function indexObjectsByProperty(records, keyProperty = "id") {
  if (!Array.isArray(records)) {
    throw new TypeError("Expected records to be an Array instance.");
  }
  if (typeof keyProperty !== "string" || keyProperty.trim().length === 0) {
    throw new TypeError("Expected keyProperty to be a non-empty string.");
  }

  try {
    const cleanKeyProp = keyProperty.trim();
    const indexedMap = new Map();

    for (let i = 0; i < records.length; i += 1) {
      const item = records[i];
      if (typeof item !== "object" || item === null || Array.isArray(item)) {
        throw new TypeError(`Expected item at index ${i} to be a non-null plain/record object.`);
      }

      const hasKey = Object.prototype.hasOwnProperty.call(item, cleanKeyProp);
      const rawKey = hasKey ? item[cleanKeyProp] : undefined;

      if (typeof rawKey !== "string" && typeof rawKey !== "number") {
        throw new TypeError(`Expected property "${cleanKeyProp}" at index ${i} to be a string or number.`);
      }

      const lookupKey = String(rawKey).trim();
      if (lookupKey.length === 0) {
        throw new TypeError(`Property "${cleanKeyProp}" at index ${i} cannot be empty.`);
      }

      indexedMap.set(lookupKey, item);
    }

    return indexedMap;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed indexing objects by property "${keyProperty}": ${message}`);
  }
}

// Example usage:
// try {
//   const products = [
//     { sku: "SKU-1", title: "Mechanical Keyboard", price: 14500 },
//     { sku: "SKU-2", title: "USB-C Dock", price: 9800 }
//   ];
//   const skuMap = indexObjectsByProperty(products, "sku");
//   console.log("Matched product:", skuMap.get("SKU-2")?.title); // "USB-C Dock"
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Use Map rather than {} when keying objects by dynamic IDs or strings: Avoids collisions with Object.prototype properties (constructor, toString, hasOwnProperty).
  • Decide whether duplicate keys should overwrite or throw: Map.prototype.set() overwrites earlier entries with the same key unless you explicitly check indexedMap.has(lookupKey) first.

3. Sparse Arrays, null / Primitive Elements, and Mutability Caveats

Keep these object-array iteration edge cases in mind in production JavaScript:

  • Never assume every element in an array is a plain object: API responses or user inputs can contain null, undefined, primitives, or nested arrays—validate each item before accessing properties.
  • Avoid for...in on arrays: for...in iterates enumerable property keys (including custom enumerable properties on the array or prototype) rather than cleanly walking array indices in order.
  • Watch object reference mutation during loops: Modifying item.someProp = ... inside a loop mutates the original object in place; clone or construct a new object/value when immutability is required.