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

Flatten nested object using lodash

1个答案

1

When flattening nested objects with the Lodash library, a common approach is to utilize the _.flattenDeep function. However, this function is limited to handling nested arrays. For nested objects, we need a different strategy, such as implementing a custom recursive function to flatten the objects.

Here is an example using Lodash and custom recursive logic to flatten nested objects:

1. Install Lodash

First, ensure Lodash is installed in your project:

bash
npm install lodash

2. Write the Flattening Function

We will create a function that recursively traverses all levels of the nested object, converting it into a flat object with key-value pairs at the top level. The key names will include path information, separated by dots.

javascript
const _ = require('lodash'); function flattenObject(obj, prefix = '') { return _.transform(obj, (result, value, key) => { const newKey = prefix ? `${prefix}.${key}` : key; if (_.isObject(value) && !_.isArray(value)) { _.assign(result, flattenObject(value, newKey)); } else { result[newKey] = value; } }); }

3. Use the Flattening Function

Suppose we have the following nested object:

javascript
const nestedObject = { level1: { level2: { level3: 'value1' }, level2b: 'value2' }, level1b: 'value3' }; const flatObject = flattenObject(nestedObject); console.log(flatObject);

Output Result

Running this code produces the following output:

javascript
{ 'level1.level2.level3': 'value1', 'level1.level2b': 'value2', 'level1b': 'value3' }

Thus, the nested object is flattened into a flat object with key-value pairs at the top level, where each key represents the path from the root to the value.

This method is highly useful when working with complex data structures, especially when you need to quickly retrieve or manipulate data across different levels.

2024年6月29日 12:07 回复

你的答案