Câu hỏi phỏng vấn Javascript
Câu hỏi

How to compare two objects in JavaScript?

Câu trả lời

Comparing two objects in JavaScript can be a complex task due to the nature of objects in the language. Here are the primary methods and considerations for comparing objects:

1. Using Strict Equality (===)

JavaScript provides the === operator for strict equality comparison. However, this operator only checks if two objects are the same instance, not if they have the same content. For example:

javascript Copy
const obj1 = { a: 1 };
const obj2 = { a: 1 };
console.log(obj1 === obj2); // Outputs: false

This returns false because obj1 and obj2 are different instances in memory[4].

2. Shallow Comparison

A shallow comparison checks if two objects have the same top-level properties with the same values. This method does not check nested objects deeply. Here's a simple implementation:

javascript Copy
function shallowEqual(obj1, obj2) {
    const keys1 = Object.keys(obj1);
    const keys2 = Object.keys(obj2);

    if (keys1.length !== keys2.length) {
        return false;
    }

    for (let key of keys1) {
        if (obj1[key] !== obj2[key]) {
            return false;
        }
    }

    return true;
}

This function will return true if all top-level properties match in both value and type[3].

3. Deep Comparison

For a more thorough comparison, a deep comparison function checks every level of nested objects or arrays. This can be done using a recursive function or a library like Lodash with its _.isEqual() function, which handles deep comparison effectively:

javascript Copy
const _ = require('lodash');
const obj1 = { a: { b: 2 } };
const obj2 = { a: { b: 2 } };
console.log(_.isEqual(obj1, obj2)); // Outputs: true

Lodash's _.isEqual() method performs a deep comparison between two values to determine if they are equivalent, handling various edge cases like circular references and special object types[2][5].

4. Using JSON.stringify()

Another approach is converting objects to JSON strings and comparing these strings:

javascript Copy
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };
console.log(JSON.stringify(obj1) === JSON.stringify(obj2)); // Outputs: true

However, this method has limitations. It fails when the properties are in different orders, and it doesn't handle Date objects or func...

middle

middle

Gợi ý câu hỏi phỏng vấn

middle

Why is extending built-in JavaScript objects not a good idea?

middle

What's the difference between .call and .apply ?

middle

What are the advantages and disadvantages of using use strict ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào