使用Lodash实现复杂JSON格式映射的技术求助
Data Mapping Solutions with Lodash
Got it, let's tackle your two data transformation needs one by one using Lodash—this library simplifies these kinds of mapping tasks so much.
1. Convert Object of Arrays to Array of Arrays with Key
First up, transforming your object of arrays into an array of arrays where each entry includes the original key as the last element.
Original Structure
const sourceData = { types: { one: [0.0954835843, 6.054385, 84.40238], two: [0.0954835843, 6.054385, 84.40238], three: [0.0954835843, 6.054385, 84.40238] } };
Transformation Code
We'll use _.entries to extract key-value pairs from the object, then _.map to restructure each entry:
const transformedTypes = _.map(_.entries(sourceData.types), ([key, values]) => [...values, key]);
Result
[ [0.0954835843, 6.054385, 84.40238, 'one'], [0.0954835843, 6.054385, 84.40238, 'two'], [0.0954835843, 6.054385, 84.40238, 'three'] ]
How It Works
_.entries(sourceData.types)converts the object into an array of[key, value]pairs (e.g.,['one', [0.0954835843, ...]]).- We use array destructuring in the
_.mapcallback to grab thekeyandvaluesarray, then spread the values and append the key to form the final array.
2. Match Data by ID Across Two Collections
For your second need—combining data from two collections using ID matches—Lodash's lookup utilities make this efficient. Let's assume you have two datasets like this:
Example Datasets
// Your first collection with ID and data const types = [ { id: 1, data: [ ['temp', '46%', '14.00', '1388.68561604'] ] }, { id: 2, data: [ ['humidity', '72%', '22.50', '987.12345'] ] } ]; // Second collection with matching IDs and additional info const metadata = [ { id: 1, label: 'Sensor A', location: 'Living Room' }, { id: 2, label: 'Sensor B', location: 'Bedroom' } ];
Transformation Code
First, create a quick lookup map with _.keyBy, then merge the data with _.map:
// Create a lookup map for fast ID-based access (O(1) lookups) const metadataMap = _.keyBy(metadata, 'id'); // Merge matching entries from both collections const mergedData = _.map(types, typeEntry => { const matchedMetadata = metadataMap[typeEntry.id]; // Customize the merge based on your needs—here we combine all fields return { ...typeEntry, ...matchedMetadata }; });
Result
[ { id: 1, data: [ ['temp', '46%', '14.00', '1388.68561604'] ], label: 'Sensor A', location: 'Living Room' }, { id: 2, data: [ ['humidity', '72%', '22.50', '987.12345'] ], label: 'Sensor B', location: 'Bedroom' } ]
How It Works
_.keyBy(metadata, 'id')converts the metadata array into an object where keys are IDs and values are the metadata entries (e.g.,{ 1: { id:1, label: 'Sensor A', ... }, ... })._.mapiterates over each entry intypes, finds the matching metadata via the lookup map, and merges the two objects. This is way more efficient than using_.findinside the map (which would be O(n²) instead of O(n)).
内容的提问来源于stack exchange,提问作者susanoo
相关产品推荐
相关产品推荐

