乐闻世界logo
搜索文章和话题

Convert all object values to lowercase with lodash

1个答案

1

When working with JavaScript objects, it's common to perform various transformations on their values, such as converting all string values to lowercase. Using the lodash library simplifies this process. lodash is a widely used JavaScript utility library offering many functions for handling arrays, numbers, objects, and strings.

To convert all string values in an object to lowercase, we can utilize the mapValues function from lodash, which iterates through each property value and applies a transformation function you specify. If the value is a string, we can convert it to lowercase using the toLowerCase() method of the String prototype.

Here's a concrete example:

Suppose we have the following object:

javascript
const obj = { Name: 'ALICE', Age: 25, Role: 'DEVELOPER' };

We want to convert all string values to lowercase. We can write the following code:

javascript
import _ from 'lodash'; const lowerCaseValues = _.mapValues(obj, val => typeof val === 'string' ? val.toLowerCase() : val ); console.log(lowerCaseValues);

The output of this code will be:

javascript
{ Name: 'alice', Age: 25, Role: 'developer' }

In this example, mapValues iterates through each property value of the obj object. The arrow function val => typeof val === 'string' ? val.toLowerCase() : val checks if each value is a string. If it is, it converts the string to lowercase using toLowerCase(). If not, it returns the original value.

This method is highly useful, particularly when working with objects containing mixed data types, as it ensures that only string values are modified while other types, such as numbers, remain unchanged. This helps prevent type errors and makes the code more robust and maintainable.

2024年8月24日 01:34 回复

你的答案