如何遵循DRY原则优化映射函数?解决重复map调用问题
Optimizing Map Calls to Follow DRY Principle
Great question! Repeating jsonData.data.map() calls like that not only violates the DRY (Don't Repeat Yourself) principle but also wastes resources by looping through the same array multiple times. Here are a couple of clean, efficient ways to fix this:
Method 1: Use Array.reduce() (Most Direct)
With reduce, you can iterate through the data array only once and build your mainContainer object incrementally:
var jsonData = { "data": [ { "id": 1, "name": "London", "date": "2018-04-20", "temp": 15, "rain": 2, "wind": 50, "humidity" : 80 } ] }; const mainContainer = jsonData.data.reduce((acc, item) => { acc.temp.push(item.temp); acc.rain.push(item.rain); acc.wind.push(item.wind); acc.humidity.push(item.humidity); return acc; }, { temp: [], rain: [], wind: [], humidity: [] });
How it works:
- We start with an initial accumulator object (
acc) that matches the structure you want formainContainer, with empty arrays for each field. - For every item in the data array, we push the corresponding values into each array in the accumulator.
- By the end of the loop, we have fully populated all arrays in
mainContainerwith just one pass through the data.
Method 2: Use forEach with a Field List (More Scalable)
If you anticipate adding more fields later, this approach makes it easy to update without rewriting the core logic:
var jsonData = { "data": [ { "id": 1, "name": "London", "date": "2018-04-20", "temp": 15, "rain": 2, "wind": 50, "humidity" : 80 } ] }; // Define the fields you want to extract const targetFields = ['temp', 'rain', 'wind', 'humidity']; // Initialize mainContainer with empty arrays for each field const mainContainer = Object.fromEntries( targetFields.map(field => [field, []]) ); // Loop through the data once to populate all arrays jsonData.data.forEach(item => { targetFields.forEach(field => { mainContainer[field].push(item[field]); }); });
How it works:
- We first define all the fields we need in an array (
targetFields). Object.fromEntriesconverts the field list into our initialmainContainerstructure with empty arrays.- We loop through the data array once, and for each item, we push values into all relevant arrays in one go.
- To add a new field later, you just need to add it to
targetFields—no other code changes required!
Both approaches eliminate repeated map calls, follow DRY, and are more efficient since they only iterate through your data array once.
内容的提问来源于stack exchange,提问作者lovemyjob
相关产品推荐
相关产品推荐

