Example 1: Getting the differences between two objects javascript lib
import { transform, isEqual, isObject } from 'lodash';
function difference(object, base) {
return transform(object, (result, value, key) => {
if (!isEqual(value, base[key])) {
result[key] = isObject(value) && isObject(base[key]) ? difference(value, base[key]) : value;
}
});
}
Example 2: Javascript compare two objects
var person1={first_name:"bob"};
var person2 = {first_name:"bob"};
if(JSON.stringify(person1) === JSON.stringify(person2)){
}
Example 3: diffrence of two objects javascript
const { inspect } = require('util')
const transform = require('lodash.transform')
const isEqual = require('lodash.isequal')
const isArray = require('lodash.isarray')
const isObject = require('lodash.isobject')
function difference(origObj, newObj) {
function changes(newObj, origObj) {
let arrayIndexCounter = 0
return transform(newObj, function (result, value, key) {
if (!isEqual(value, origObj[key])) {
let resultKey = isArray(origObj) ? arrayIndexCounter++ : key
result[resultKey] = (isObject(value) && isObject(origObj[key])) ? changes(value, origObj[key]) : value
}
})
}
return changes(newObj, origObj)
}
const originalObject = {
foo: 'bar',
baz: 'fizz',
cool: true,
what: {
one: 'one',
two: 'two'
},
wow: {
deep: {
key: ['a', 'b', 'c'],
values: '123'
}
},
array: ['lol', 'hi', 'there']
}
const newObject = {
foo: 'bar',
baz: 'fizz',
cool: false,
what: {
one: 'one',
two: 'twox'
},
wow: {
deep: {
key: ['x', 'y', 'c'],
values: '098'
}
},
array: ['lol', 'hi', 'difference']
}
const diff = difference(originalObject, newObject)
console.log(inspect(diff, {showHidden: false, depth: null, colors: true}))
if (diff.cool) {
console.log('Coolness changed to', diff.cool)
}
Example 4: object difference javascript
const { inspect } = require('util')
const { transform, isEqual, isArray, isObject } = require('lodash')
function difference(origObj, newObj) {
function changes(newObj, origObj) {
let arrayIndexCounter = 0
return transform(newObj, function (result, value, key) {
if (!isEqual(value, origObj[key])) {
let resultKey = isArray(origObj) ? arrayIndexCounter++ : key
result[resultKey] =
isObject(value) && isObject(origObj[key])
? changes(value, origObj[key])
: value
}
})
}
return changes(newObj, origObj)
}
const originalObject = {
foo: 'bar',
baz: 'fizz',
cool: true,
what: {
one: 'one',
two: 'two'
},
wow: {
deep: {
key: ['a', 'b', 'c'],
values: '123'
}
},
array: ['lol', 'hi', 'there']
}
const newObject = {
foo: 'bar',
baz: 'fizz',
cool: false,
what: {
one: 'one',
two: 'twox'
},
wow: {
deep: {
key: ['x', 'y', 'c'],
values: '098'
}
},
array: ['lol', 'hi', 'difference']
}
const diff = difference(originalObject, newObject)
console.log(inspect(diff, {showHidden: false, depth: null, colors: true}))
if (diff.cool) {
console.log('Coolness changed to', diff.cool)
}