如何在NodeJS中合并JSON数组元素并按Job Number聚合生成新JSON数组
Absolutely! This is totally achievable with basic array manipulation and grouping logic—let me walk you through how to do it step by step.
Step-by-Step Explanation
Here's the core approach we'll use:
- First, group all objects by their
Job Number—this lets us handle each job's data as a single set. - For each group, calculate the three required aggregated values:
Total Tax Amount: Sum allTax Amountvalues in the groupSum of Tax Items: SumLineTotalonly for objects whereTax Amountis greater than 0Sum of non tax items: SumLineTotalonly for objects whereTax Amountequals 0
- Finally, convert the grouped data back into a JSON array format.
Example Code (JavaScript)
Since you mentioned having basic array knowledge, here's a practical implementation using JavaScript (you can adapt this logic to other languages like Python, Java, etc., with similar grouping/aggregation functions):
// Your input JSON array const inputData = [ { "Job Number":200, "Tax Amount":5.00, "LineTotal":12, "Line Total plus tax":17.00 }, { "Job Number":200, "Tax Amount":2.00, "LineTotal":10, "Line Total plus tax":12.00 }, { "Job Number":200, "Tax Amount":0.00, "LineTotal":8, "Line Total plus tax":8 } ]; // Step 1: Group data by Job Number using reduce() const groupedData = inputData.reduce((acc, item) => { const jobNumber = item["Job Number"]; // If this job number isn't in the accumulator yet, initialize it if (!acc[jobNumber]) { acc[jobNumber] = { "Job Number": jobNumber, "Total Tax Amount": 0, "Sum of Tax Items": 0, "Sum of non tax items": 0 }; } // Step 2: Calculate aggregated values acc[jobNumber]["Total Tax Amount"] += item["Tax Amount"]; if (item["Tax Amount"] > 0) { acc[jobNumber]["Sum of Tax Items"] += item["LineTotal"]; } else { acc[jobNumber]["Sum of non tax items"] += item["LineTotal"]; } return acc; }, {}); // Step 3: Convert the grouped object back to an array const outputData = Object.values(groupedData); console.log(JSON.stringify(outputData, null, 2));
Output Result
Running this code will give you exactly the output you're looking for:
[ { "Job Number": 200, "Total Tax Amount": 7.00, "Sum of Tax Items": 22.00, "Sum of non tax items": 8 } ]
Adapting to Other Languages
If you're using a different language, the logic stays the same:
- Python: Use
itertools.groupbyor a dictionary to group items, then loop through each group to calculate sums. - Java: Use a
Map<Integer, AggregatedJob>whereAggregatedJobholds your summed values, then convert the map values to a list.
This pattern works perfectly even with 100+ objects—grouping and aggregation are standard operations for this kind of data processing.
内容的提问来源于stack exchange,提问作者ItalianDadx2

