0

I am trying to get the change object from two objects using typescript in angular.

For example

this.productPreviousCommand = {
"id": "60f910d7d03dbd2ca3b3dfd5",
"active": true,
"title": "ss",
"description": "<p>ss</p>",
"category": {
    "id": "60cec05df64bde4ab9cf7460"
},
"subCategory": {
    "id": "60cec18c56d3d958c4791117"
},
"vendor": {
    "id": "60ced45b56d3d958c479111c"
},
"type": "load_product_success"

}

model = {
"active": true,
"title": "ss",
"description": "<p>ss sss</p>",
"category": "60cec05df64bde4ab9cf7460",
"subCategory": "60cec18c56d3d958c4791117",
"vendor": "60ced45b56d3d958c479111c",
"tags": []

}

Now the difference between two objects are description: "<p>hello hello 1</p>". So I want to return {description: "<p>hello hello 1</p>"}

I used lodash https://github.com/lodash/lodash

import { transform, isEqual, isObject, isArray} from '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)
}

This library is not working for me, it returns the whole object using this code const differenc = difference(this.productPreviousCommand, model);

The output of above code is

{
    active: true
    description: "<p>hello hello 1</p>"
    id: "60f8f29dd03dbd2ca3b3dfd1"
    title: "hello"
    }
San Jaisy
  • 15,327
  • 34
  • 171
  • 290
  • Is the code you posted yours or the one of Lodash? I don't see any `difference` function in Lodash documentation except to compare arrays. If it's yours, you'll need to provide us with a specific question after debugging. – Gaël J Jul 22 '21 at 05:49
  • Does this answer your question? [jQuery function to compute the difference between two JavaScript objects](https://stackoverflow.com/questions/11021893/jquery-function-to-compute-the-difference-between-two-javascript-objects) – Gaël J Jul 22 '21 at 05:51
  • @GaëlJ it is not one of Lodash, however I found it here https://www.codegrepper.com/code-examples/javascript/javascript+compare+two+objects+and+get+differences – San Jaisy Jul 22 '21 at 06:02
  • refer this example http://jsfiddle.net/drzaus/9g5qoxwj/ – Parth M. Dave Jul 22 '21 at 06:20

3 Answers3

1

Try this function

differenceInObj(firstObj: any, secondObj: any): any {
        let differenceObj: any = {};
        for (const key in firstObj) {
            if (Object.prototype.hasOwnProperty.call(firstObj, key)) {
                if(firstObj[key] !== secondObj[key]) {
                    differenceObj[key] = firstObj[key];
                }
                
            }
        }

        return differenceObj;
    }
0

function difference(origObj, newObj) {
  const origObjKeyList = Object.keys(origObj),
    newObjKeyList = Object.keys(newObj);

  // if objects length is not same
  if (origObjKeyList?.length !== newObjKeyList?.length) {
    return;
  }

  // if object keys some difference in keys
  if (Object.keys(origObj).filter((val) => !Object.keys(newObj).includes(val))?.length) {
    return;
  }

  return Object.entries(origObj).reduce(
    (acc, [key, value]) => (newObj[key] !== value ? { ...acc, ...{ [key]: newObj[key] } } : acc),
    []
  );
}


const a = {
  active: true,
  description: '<p>hello</p>',
  id: '60f8f29dd03dbd2ca3b3dfd1',
  title: 'hello',
};

const b = {
  active: true,
  description: '<p>hello hello 1</p>',
  id: '60f8f29dd03dbd2ca3b3dfd1',
  title: 'hello',
};


console.log(difference(a, b));

You can try this code.

function difference(origObj, newObj) {
  const origObjKeyList = Object.keys(origObj),
    newObjKeyList = Object.keys(newObj);

  // if objects length is not same
  if (origObjKeyList?.length !== newObjKeyList?.length) {
    return;
  }

  // if object keys is not same
  if (Object.keys(origObj).filter((val) => !Object.keys(newObj).includes(val))?.length) {
    return;
  }

  return Object.entries(origObj).reduce(
    (acc, [key, value]) => (newObj[key] !== value ? { ...acc, ...{ [key]: newObj[key] } } : acc),
    []
  );
}
Deepanshu Gupta
  • 240
  • 1
  • 5
0

You can check loop through each key of the first object and compare it with the second object.

function getPropertyDifferences(obj1, obj2) {
  return Object.entries(obj1).reduce((diff, [key, value]) => {
    // Check if the property exists in obj2.
    if (obj2.hasOwnProperty(key)) {
      const val = obj2[key];

      // Check if obj1's property's value is different from obj2's.
      if (val !== value) {
        return {
          ...diff,
          [key]: val,
        };
      }
    }

    // Otherwise, just return the previous diff object.
    return diff;
  }, {});
}

const a = {
  active: true,
  description: '<p>hello</p>',
  id: '60f8f29dd03dbd2ca3b3dfd1',
  title: 'hello',
};
const b = {
  active: true,
  description: '<p>hello hello 1</p>',
  id: '60f8f29dd03dbd2ca3b3dfd1',
  title: 'hello',
};
const c = {
  active: true,
  description: '<p>hello hello 2</p>',
  id: '60f8f29dd03dbd2ca3b3dfd1',
  title: 'world',
};

console.log(getPropertyDifferences(a, b));
console.log(getPropertyDifferences(b, c));
dork
  • 4,396
  • 2
  • 28
  • 56