@rbxts/jsnatives
Object.equals
Determines whether two objects have the same properties with equal values.
Signature
function equals<T, U>(obj: T, other: U, deep?: boolean): obj is T & U
Description
The Object.equals()
method performs a content-based comparison between two objects. It returns true
if both objects have the same structure and content, and false
otherwise.
By default, Object.equals()
performs a shallow comparison, where nested objects are compared by reference. By passing true
as the third parameter, you can perform a deep comparison, where the contents of nested objects are also compared.
Examples
Basic object comparison
const objA = {a: 1, b: 2, c: 3};const objB = {a: 1, b: 2, c: 3};const objC = {a: 1, b: 2, c: 4};
print(Object.equals(objA, objB)); // true (same properties and values)print(Object.equals(objA, objC)); // false (different value for property 'c')
Working with proxies
const proxiedObj = new Proxy({a: 1, b: 2, c: 3}, {});const regularObj = {a: 1, b: 2, c: 3};
print(Object.equals(proxiedObj, regularObj)); // true (same properties and values)
Comparing different object types
const map = new Map([["a", 1], ["b", 2], ["c", 3]]);const set = new Set([1, 2, 3]);const array = [1, 2, 3];
print(Object.equals(map, set)); // false (different structures)print(Object.equals(map, array)); // false (different structures)print(Object.equals(set, array)); // false (different structures)
Deep comparison
const nestedObjA = {a: 1, b: 2, c: 3, d: {e: 4, f: 5}};const nestedObjB = {a: 1, b: 2, c: 3, d: {e: 4, f: 5}};const nestedObjC = {a: 1, b: 2, c: 3, d: {e: 4, f: 6}};
// By default, nested objects are compared by referenceprint(Object.equals(nestedObjA, nestedObjB)); // false (d's reference is different)
// With deep=true, nested objects are compared by contentprint(Object.equals(nestedObjA, nestedObjB, true)); // true (d's contents are equal)print(Object.equals(nestedObjA, nestedObjC, true)); // false (d's f property has different value)
Type narrowing with equals
function processObjects<T, U>(objA: T, objB: U) { if (Object.equals(objA, objB)) { // In this block, objA and objB are typed as T & U return "Objects are equal"; } else { // In this block, objA is T and objB is U return "Objects are different"; }}