技术问询:寻求基于JSON格式的Lodash difference函数实现方案
Got it, I totally get the frustration when standard Lodash functions don’t behave as expected with complex JSON objects—since _.difference relies on strict equality (checking either primitive value matches or object references), it won’t recognize objects that have identical content but different memory references as being the same. Let’s fix that with a tailored solution.
The Core Issue
Out of the box, _.difference uses the SameValueZero algorithm for comparisons. For JSON objects, this means two objects are only considered equal if they point to the exact same reference in memory—even if their keys and values are identical. That’s rarely what we want when working with JSON data.
The Solution: Use _.differenceWith + _.isEqual
Lodash already has the tools we need: _.differenceWith lets you define a custom comparison function, and _.isEqual performs a deep comparison of values (perfect for JSON objects). Here’s how to combine them:
Basic Example
Suppose we have two arrays of JSON objects:
const originalData = [ { id: 1, username: "jane_doe", email: "jane@example.com" }, { id: 2, username: "john_smith", email: "john@example.com" } ]; const updatedData = [ { id: 2, username: "john_smith", email: "john@example.com" }, { id: 3, username: "sarah_jones", email: "sarah@example.com" } ];
To get the objects that exist in originalData but not in updatedData (using deep equality):
const jsonDifference = _.differenceWith(originalData, updatedData, _.isEqual); // Result: [{ id: 1, username: "jane_doe", email: "jane@example.com" }]
Custom Comparison Logic
If you only need to compare specific properties (e.g., just the id field) instead of the entire object, you can write a custom comparison function:
const differenceById = _.differenceWith(originalData, updatedData, (a, b) => a.id === b.id); // Result is the same as above, since we're matching on id
Reusable Function
For convenience, wrap this logic into a reusable function:
function getJsonDifference(arr1, arr2) { // Ensure we're working with valid arrays first if (!Array.isArray(arr1) || !Array.isArray(arr2)) { throw new Error("Both arguments must be arrays"); } return _.differenceWith(arr1, arr2, _.isEqual); } // Usage const uniqueItems = getJsonDifference(originalData, updatedData);
Notes
_.isEqualhandles most JSON-compatible types: objects, arrays, strings, numbers, booleans, and even special types likeDateorRegExpif needed.- For very large datasets, keep in mind that deep comparisons can be slower than shallow checks—if performance is critical, consider comparing a unique identifier (like
id) instead of the full object.
内容的提问来源于stack exchange,提问作者AmazingDayToday

