Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sejalkailashyadav/e97a46b0d7e9e72862a8fae6bab0801c to your computer and use it in GitHub Desktop.
Save sejalkailashyadav/e97a46b0d7e9e72862a8fae6bab0801c to your computer and use it in GitHub Desktop.

Immutable Deep Update using Nested Maps:


πŸ” Immutable Deep Update using Nested Maps

When working with nested data structures like arrays of objects (e.g., departments with employees), it's important to update values immutably β€” without modifying the original data.
This pattern uses nested .map() functions to update specific fields deep within the structure.


✨ Use Case

Change an employee's skill from "Go" to "Rust" in a nested departments array.


πŸ“¦ Sample Data

const departments = [
  {
    name: "Engineering",
    employees: [
      { name: "Alice", skills: ["JavaScript", "Python", "Recruitment"] },
      { name: "Bob", skills: ["Java", "Go"] }
    ]
  },
  {
    name: "HR",
    employees: [
      { name: "Charlie", skills: ["Recruitment"] }
    ]
  }
];

βœ… Goal

Update Bob’s "Go" skill to "Rust" immutably (without changing the original array).


🧠 Solution: Nested .map() for Deep Update

const updatedDepartments = departments.map(department => ({
  ...department,
  employees: department.employees.map(employee => {
    if (employee.name === "Bob") {
      return {
        ...employee,
        skills: employee.skills.map(skill =>
          skill === "Go" ? "Rust" : skill
        )
      };
    }
    return employee;
  })
}));

πŸ§ͺ Result

console.log(updatedDepartments);

Output:

[
  {
    name: "Engineering",
    employees: [
      { name: "Alice", skills: ["JavaScript", "Python", "Recruitment"] },
      { name: "Bob", skills: ["Java", "Rust"] }
    ]
  },
  {
    name: "HR",
    employees: [
      { name: "Charlie", skills: ["Recruitment"] }
    ]
  }
]

🧾 Summary

  • βœ… Keeps original data intact (no mutations).
  • βœ… Scales well for updating deep nested objects.
  • βœ… Useful in React state updates or functional programming
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment