如何使用Lodash比较两个对象并返回指定结构的新对象?
Solution to Match and Extract Data Between Two Objects
Alright, let's tackle this problem where we need to find entries in object1 whose names exist in object2, then extract specific fields to build our desired object3. Here's a clean, efficient approach using JavaScript:
Step-by-Step Implementation
First, let's define our input objects clearly:
const object1 = { "body": { "items": [ { "data": { "name": "Smith", "status": "Ready", "userinfo": [ { "dob": "01/01/2000", "nickname": "Joe" } ] }, "workinfo": { "company": "mycompany", "address": "101 Main str." } }, { "data": { "name": "Luke", "status": "Ready", "userinfo": [ { "dob": "01/01/2001", "nickname": "LL" } ] }, "workinfo": { "company": "mycompany", "address": "101 Main str." } } ] } }; const object2 = { "items": [ { "name": "Smith", "status": "Ready" }, { "name": "Luke", "status": "Ready" } ] };
Basic Matching (Name Only)
If we just need to match by name and extract name + status from object1:
// Create a Set of valid names from object2 for fast lookup const validNames = new Set(object2.items.map(item => item.name)); // Filter and transform the data from object1 const object3 = object1.body.items .filter(item => validNames.has(item.data.name)) .map(item => ({ name: item.data.name, status: item.data.status })); console.log(object3); // Output: // [ { name: 'Smith', status: 'Ready' }, { name: 'Luke', status: 'Ready' } ]
Enhanced Matching (Name + Status)
If you need to ensure both name and status match between the two objects:
// Create a Map to link names to their expected status from object2 const userStatusMap = new Map(object2.items.map(item => [item.name, item.status])); const object3 = object1.body.items .filter(item => { const expectedStatus = userStatusMap.get(item.data.name); // Check if the name exists AND status matches return expectedStatus && expectedStatus === item.data.status; }) .map(item => ({ name: item.data.name, status: item.data.status }));
Key Explanations
- Set for Fast Lookup: Using a
Set(orMapfor enhanced matching) makes checking if a name exists much faster than looping throughobject2.itemsevery time—critical if you're working with large datasets. - Filter + Map: The combination of
filter(to keep only matching entries) andmap(to reshape the data into our desired format) is a concise, readable way to process the array.
内容的提问来源于stack exchange,提问作者John Glabb
相关产品推荐
相关产品推荐

