如何对比两个文件数组对象的公共字段并更新数组?
How to Compare & Merge Array Objects by Common Field (with Update Logic)
Got it, let's walk through how to tackle this problem: comparing objects across two arrays using a shared identifier field (organizationId in your example) and merging/updatingFind f.geningerton importanceselling manager� important引原的例子里) and merging/updating them to get your desired output.
First, let's clarify the core logic from your examples:
- Objects with the same
organizationIdshould have their fields merged, with values from the second array overriding any conflicting fields from the first (like howkey1fororg1changes fromvalue1tovalue4). - Objects that only exist in one array should be kept as-is in the final output.
Example Inputs & Expected Output
input1.json
[ { "organizationId": "org1", "test1": "UP", "key1": "value1" }, { "organizationId": "org2", "test1": "UP", "key1": "value3" } ]
input2.json
[ { "organizationId": "org1", "test2": "DOWN", "key1": "value4" }, { "organizationId": "org3", "test2": "DOWN", "key1": "value5" } ]
Expected output.json
[ { "organizationId": "org1", "test1": "UP", "key1": "value4", "test2": "DOWN" }, { "organizationId": "org2", "test1": "UP", "key1": "value3" }, { "organizationId": "org3", "test2": "DOWN" } ]
Solution 1: JavaScript (Plain JS)
This approach uses maps for fast lookups and spread syntax to merge objects cleanly:
// Load your JSON data into these variables (e.g., via fetch, fs.readFile, etc.) const input1 = [ { "organizationId": "org1", "test1": "UP", "key1": "value1" }, { "organizationId": "org2", "test1": "UP", "key1": "value3" } ]; const input2 = [ { "organizationId": "org1", "test2": "DOWN", "key1": "value4" }, { "organizationId": "org3", "test2": "DOWN", "key1": "value5" } ]; // Step 1: Convert arrays to dictionaries keyed by organizationId const orgMap = input1.reduce((acc, obj) => { acc[obj.organizationId] = { ...obj }; // Copy to avoid mutating original return acc; }, {}); // Step 2: Merge input2 into the map, overriding existing fields input2.forEach(obj => { const orgId = obj.organizationId; orgMap[orgId] = orgMap[orgId] ? { ...orgMap[orgId], ...obj } : { ...obj }; }); // Step 3: Convert the map back to an array const output = Object.values(orgMap); // Log or save the formatted output console.log(JSON.stringify(output, null, 2));
How this JS code works:
- We use
reduceto turn the first array into a dictionary where each key is anorganizationId—this lets us look up objects in O(1) time instead of looping through the array every time. - Forowe more(withVN弹 Fast那么几 JudBLANK>
- Finally,
Object.values()converts the merged dictionary back into an array of objects, which matches your expected output.
Solution 2: Python
If you're working in Python, here's a straightforward implementation:
import json # Load your JSON data (replace with file reading logic if needed) input1 = [ {"organizationId": "org1", "test1": "UP", "key1": "value1"}, {"organizationId": "org2", "test1": "UP", "key1": "value3"} ] input2 = [ {"organizationId": "org1", "test2": "DOWN", "key1": "value4"}, {"organizationId": "org3", "test2": "DOWN", "key1": "value5"} ] # Initialize a dictionary to track merged objects by organizationId merged_dict = {} # Add all entries from input1 first for item in input1: org_id = item["organizationId"] merged_dict[org_id] = item.copy() # Copy to avoid modifying original data # Update with entries from input2: merge existing, add new for item in input2: org_id = item["organizationId"] if org_id in merged_dict: merged_dict[org_id].update(item) # Overwrites existing fields with input2 values else: merged_dict[org_id] = item.copy() # Convert the dictionary back to a list output = list(merged_dict.values()) # Print or save the formatted output print(json.dumps(output, indent=2))
How this Python code works:
- We first populate a dictionary with all objects from
input1, usingorganizationIdas the key. - For each object in
input2, if the ID exists in the dictionary, we useupdate()to merge the new fields (overwriting any duplicates). If not, we add the new object to the dictionary. - The final step converts the dictionary's values into an array, which matches your expected output structure.
内容的提问来源于stack exchange,提问作者Naveen K Reddy
相关产品推荐
相关产品推荐

