Ticker

6/recent/ticker-posts

How to check that two objects have the same set of property names and values! (javascipt or typescript)!

 

 

 


 

 

// ============================
// Basic
// ============================
const data1 = {firstName: 'John', lastName: 'Smith'};
const data2 = {firstName: 'Jane', lastName: 'Smith'};
JSON.stringify(data1) === JSON.stringify(data2)
// => true


// ============================
// Basic 2
// ============================
// lodash
const _ = require('lodash');

const object = { 'a': 1 };
const other = { 'a': 1 };
_.isEqual(object, other);
// => true


// ============================
// advanced 1
// ============================
function deepEqual(object1, object2) {
const keys1 = Object.keys(object1);
const keys2 = Object.keys(object2);
if (keys1.length !== keys2.length) {
return false;
}
for (const key of keys1) {
const val1 = object1[key];
const val2 = object2[key];
const areObjects = isObject(val1) && isObject(val2);
if (
areObjects && !deepEqual(val1, val2) ||
!areObjects && val1 !== val2
) {
return false;
}
}
return true;
}
function isObject(object) {
return object != null && typeof object === 'object';
}


const hero1 = {
name: 'Batman',
address: {
city: 'Gotham'
}
};
const hero2 = {
name: 'Batman',
address: {
city: 'Gotham'
}
};
deepEqual(hero1, hero2); // => true

// ============================
// Advanced 2
// ============================
// Node.js syntax to demonstrate the
// util.isDeepStrictEqual() method
// npm install util
// Importing util library
const util = require('util');
// Creating object1
const object1 = {
alfa: "beta",
romeo: [10, 20]
};
// Creating object2
const object2 = {
alfa: "beta",
romeo: [10, 20]
};
// Returns false
console.log("1.>", object1 == object2)
// Returns true
console.log("2.>", util.isDeepStrictEqual(object1, object2))
Reacciones:

Post a Comment

0 Comments