How do you iterate over keys, values, and nested fields in a JSON object in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you iterate over keys, values, and nested fields in a JSON object in JavaScript?

message-square
0

To iterate over keys, values, and nested fields in a JSON object in JavaScript, first parse any JSON string with JSON.parse() (wrapped in try / catch), and then iterate over own enumerable properties with Object.keys(), Object.values(), or Object.entries() (for (const [key, value] of Object.entries(obj))) rather than for...in (which walks the prototype chain). For nested objects and arrays, recurse cleanly while distinguishing Array.isArray(value) from non-null plain/nested objects (value !== null && typeof value === "object").


1. Iterating Keys, Values, and Entries with Object.* Methods

Use Object.keys(obj), Object.values(obj), or Object.entries(obj) with a for...of loop to inspect top-level keys and values safely:

// Parse JSON and iterate over keys, values, and [key, value] entries
function inspectTopLevelJson(jsonText) {
  if (typeof jsonText !== "string") {
    throw new TypeError("Expected jsonText to be a string.");
  }

  let data;
  try {
    data = JSON.parse(jsonText);
  } catch (error) {
    throw new SyntaxError(`Invalid JSON: ${error.message}`);
  }

  if (data === null || typeof data !== "object" || Array.isArray(data)) {
    throw new TypeError("Expected top-level JSON value to be an object.");
  }

  const keys = Object.keys(data);
  const values = Object.values(data);
  const entries = [];

  for (const [key, value] of Object.entries(data)) {
    entries.push({ key, value, type: typeof value });
  }

  return { keys, values, entries };
}

// Example usage:
const sample = '{"service":"billing","retries":3,"enabled":true}';
console.log(inspectTopLevelJson(sample));
  • Prefer Object.entries() over for...in: Object.entries() only visits own enumerable string keys and avoids inherited Object.prototype properties.
  • Validate top-level JSON type: A valid JSON string can parse to an object, array, string, number, boolean, or null.

2. Walking Nested Objects and Arrays with Full Paths

To visit every nested field across objects and arrays, pass an accumulated path array (such as ["user", "roles", 0]) recursively and branch on Array.isArray(node) versus non-null object nodes:

// Traverse all nested fields in a parsed JSON value and record paths + leaf values
function flattenJsonFields(node, currentPath = [], output = []) {
  if (node === null || typeof node !== "object") {
    output.push({
      path: currentPath.join("."),
      segments: [...currentPath],
      value: node
    });
    return output;
  }

  if (Array.isArray(node)) {
    if (node.length === 0) {
      output.push({
        path: currentPath.join("."),
        segments: [...currentPath],
        value: []
      });
      return output;
    }

    for (let index = 0; index < node.length; index += 1) {
      flattenJsonFields(node[index], [...currentPath, index], output);
    }
    return output;
  }

  const entries = Object.entries(node);
  if (entries.length === 0) {
    output.push({
      path: currentPath.join("."),
      segments: [...currentPath],
      value: {}
    });
    return output;
  }

  for (const [key, value] of entries) {
    flattenJsonFields(value, [...currentPath, key], output);
  }

  return output;
}

// Example usage:
const config = JSON.parse(`{
  "app": { "name": "Portal", "ports": [8080, 8443] },
  "meta": { "owner": null }
}`);

console.log(flattenJsonFields(config));
// [
//   { path: "app.name", segments: ["app", "name"], value: "Portal" },
//   { path: "app.ports.0", segments: ["app", "ports", 0], value: 8080 },
//   { path: "app.ports.1", segments: ["app", "ports", 1], value: 8443 },
//   { path: "meta.owner", segments: ["meta", "owner"], value: null }
// ]
  • Check node !== null before typeof node === "object": In JavaScript, typeof null === "object", so null is a primitive leaf value rather than a container.
  • Keep segments alongside dot paths: Retaining numeric array indices as numbers avoids ambiguity when property keys contain dots.

3. Transforming Nested Fields Non-Mutatingly

When updating or filtering nested fields inside a JSON-like structure—such as trimming strings or redacting sensitive keys—build a new object/array during recursion rather than mutating inputs in place:

// Recursively transform nested string values while redacting sensitive keys
function sanitizeJsonValue(node, redactedKeys = new Set(["password", "secret", "token"])) {
  if (node === null || typeof node !== "object") {
    return typeof node === "string" ? node.trim() : node;
  }

  if (Array.isArray(node)) {
    return node.map((item) => sanitizeJsonValue(item, redactedKeys));
  }

  const nextObj = {};
  for (const [key, value] of Object.entries(node)) {
    nextObj[key] = redactedKeys.has(key)
      ? "[REDACTED]"
      : sanitizeJsonValue(value, redactedKeys);
  }

  return nextObj;
}

// Example usage:
const rawPayload = {
  user: "  sara@example.com  ",
  auth: { token: "tok_live_999", scopes: ["read", "write"] }
};

console.log(sanitizeJsonValue(rawPayload));
// { user: "sara@example.com", auth: { token: "[REDACTED]", scopes: ["read", "write"] } }
  • Non-mutating traversal: Returning new objects and arrays preserves the original parsed data intact.
  • JSON safety: Parsed JSON is a tree of objects, arrays, strings, numbers, booleans, and null, so standard recursion without cycle handling is naturally finite.