how to use the updatewith function from lodash in javascript

The updateWith function from Lodash allows you to update a nested object property using a customizer function to determine the new value.

Here is an example usage of updateWith:

index.tsx
const _ = require('lodash');

const myObj = {
  a: {
    b: {
      c: 5
    }
  }
};

const newObject = _.updateWith(myObj, 'a.b.c', (value) => value * 2, Object);

console.log(newObject); // { a: { b: { c: 10 } } }
217 chars
14 lines

In this example, we start with an object myObj that has a nested property a.b.c with a value of 5. We use updateWith to create a new object newObject that has the same structure, but with the value of a.b.c doubled.

The third argument to updateWith is the customizer function that returns the new value of the property. In this case, we simply multiply the existing value by 2.

Note that we also pass Object as the fourth argument to updateWith. This tells Lodash to create a new object instead of modifying the original myObj object.

gistlibby LogSnag