Blog>
Snippets

Selective Properties Update with Lodash’s _.set()

Use Lodash’s _.set() method to update deeply nested properties in an object, showcasing how to avoid the verbosity of spread syntax.
// Load Lodash library
const _ = require('lodash');

// Initial object with deeply nested properties
let state = {
  user: {
    id: 1,
    name: "John Doe",
    address: {
      street: "123 Main St",
      city: "Anytown"
    }
  }
};

// Update deeply nested 'city' property using _.set()
_.set(state, 'user.address.city', 'Newtown');

// Log the updated state
console.log(state);
This code uses Lodash's _.set() method to update the 'city' property inside a deeply nested 'address' object within the 'user' object. The _.set() method takes three arguments: the original object, the path to the property to update as a string, and the new value to set. The result is that it updates 'city' to 'Newtown' without verbose copying or mutation.