Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Comparing Objects

Sometimes you will need to create two objects. They may be identical in structure but could differ in properties/value. An easy way (quick Á dirty) is to serialize them.

https://stackoverflow.com/questions/1068834/object-comparison-in-javascript


function Car(color, speed)
{
    this.Color = color;
    this.Speed = speed;
}

let car1 = new Car("Red", "Fast");
let car2 = {};
Object.assign(car2, car1);

// even though they are diff objs, this should test TRUE.
let comparison1 = (JSON.stringify(car1) === JSON.stringify(car2));
let results1 = `Are they the same? ${comparison1}`;

 

Now change one....


// now change one....
car2.Color = "Brown";
car2.Speed = "Slow";
let comparison2 = (JSON.stringify(car1) === JSON.stringify(car2));
let results2 = `Are they the same? ${comparison2}`;