how to use the setwith function from lodash in javascript

The setWith function from lodash allows us to set the value of the property in the target object using a customizer function. The customizer function provides the ability to modify the value being set, based on the current key and the parent object. The setWith function has the following signature:

index.tsx
_.setWith(object, path, value, customizer)
43 chars
2 lines

Here, object is the target object, path is the path at which to set the value, value is the value to set, and customizer is the function used to customize the setting of the value.

Here is an example usage of the setWith function:

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

const object = { a: [{ b: { c: 3 } }] };

_.setWith(object, 'a[0].b.c', 4, (value, key, parentObject) => {
  // Modify the value being set.
  // Here, we are setting the property to twice its original value.
  parentObject[key] = value * 2;
});

console.log(object.a[0].b.c); // Output: 8
319 chars
12 lines

In this example, we modified the value being set by doubling it before setting it in the parentObject. Therefore, the output of console.log(object.a[0].b.c) is 8 instead of the original 4

gistlibby LogSnag