add after ary assign assignIn assignInWith assignWith at before bind bindAll bindKey camelCase capitalize castArray ceil chain chunk clamp clone cloneDeep cloneDeepWith cloneWith compact concat conformsTo countBy create curry curryRight debounce deburr defaults defaultsDeep defer delay difference divide drop dropRight each eachRight endsWith entries entriesIn eq escape every extend extendWith fill filter find findIndex findKey findLast findLastIndex findLastKey first flatMap flatMapDeep flatMapDepth flatten flattenDeep flattenDepth flip floor forEach forEachRight forIn forInRight forOwn forOwnRight fromPairs functions functionsIn get groupBy gt gte has hasIn head inRange includes indexOf initial intersection invert invertBy invoke invokeMap isArguments isArray isArrayBuffer isArrayLike isArrayLikeObject isBoolean isBuffer isDate isElement isEmpty isEqual isEqualWith isError isFinite isFunction isInteger isLength isMap isMatch isMatchWith isNaN isNative isNil isNull isNumber isObject isObjectLike isPlainObject isRegExp isSafeInteger isSet isString isSymbol isTypedArray isUndefined isWeakMap isWeakSet join kebabCase keyBy keys keysIn last lastIndexOf lowerCase lowerFirst lt lte map mapKeys mapValues max maxBy mean meanBy memoize merge mergeWith min minBy multiply negate nth omit omitBy once orderBy overArgs pad padEnd padStart parseInt partial partialRight partition pick pickBy pull pullAll pullAllBy pullAllWith pullAt random rearg reduce reduceRight reject remove repeat replace rest result reverse round sample sampleSize set setWith shuffle size slice snakeCase some sortBy sortedIndex sortedIndexOf sortedLastIndex sortedLastIndexOf sortedUniq split spread startCase startsWith subtract sum sumBy tail take takeRight tap template throttle thru toArray toFinite toInteger toLength toLower toNumber toPairs toPairsIn toPlainObject toSafeInteger toString toUpper transform trim trimEnd trimStart truncate unary unescape union uniq uniqBy uniqWith unset unzip unzipWith update updateWith upperCase upperFirst values valuesIn without words wrap wrapperAt wrapperChain wrapperCommit wrapperFlatMap wrapperLodash wrapperNext wrapperPlant wrapperReverse wrapperToIterator wrapperValue xor zip zipObject zipObjectDeep zipWith

Lodash _.setWith

Overview

Introduction: The _.setWith() method is a utility function provided by the popular Lodash library, which provides a way to set the value of a property on an object or nested objects. This method is somewhat similar to the _.set() method, but with the added ability to customize the behavior when creating objects.

Syntax: The _.setWith() method has the following syntax.

_.setWith(object, path, value, customizer)

Parameters: The _.setWith() method accepts four parameters, which are described below.

  1. object: It is the object which we want to change.
  2. path: It is a string or an array that represents the path to the property which we want to set.
  3. value: It is the value that we want to set on the specified object's path.
  4. customizer: (Optional) It is a function that is used to customize the creation of the new object.

Return: _.setWith() method returns the modified object once the specified value has been set to the specified path.

Customizing the behavior of _.setWith(): The _.setWith() method provides a way to customize the creation of the new object. We can pass a customizer function to the _.setWith() method, which will be called for each new property that is created along the path.

The customizer function receives three arguments:

  1. The new object being created.
  2. The key of the new property.
  3. The value of the new property.

The customizer function should return the value that should be assigned to the new property. If it returns undefined, the default behavior will be used to create the new property.

Examples:

const _ = require('lodash');

// Create an object const person = { name: { first: 'John', last: 'Doe' }, age: 25 };

// Using _.setWith to set the value _.setWith(person, 'name.middle', 'Smith', Object);

console.log(person); // { name: { first: 'John', middle: 'Smith', last: 'Doe' }, age: 25 }

In the above example, we have used _.setWith() to set a new property called 'middle' on the nested object 'name'. Since there is no 'middle' property on the 'name' object, it is created by the _.setWith() method.

Conclusion: The _.setWith() method is a versatile utility function provided by the Lodash library, which allows us to set the value of a property on an object or nested objects with the added ability to customize the creation of new objects. This method can be very useful in situations where we need to modify and manipulate complex nested data structures.