1

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"
    }
4

4 Answers 4

2

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;
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Have you tested it? it is returing the whole object
let productPreviousCommand = { active: true, description: "<p>hello</p>", id: "60f8f29dd03dbd2ca3b3dfd1", title: "hello" } let model = { active: true, description: "<p>hello hello 1</p>", id: "60f8f29dd03dbd2ca3b3dfd1", title: "hello" } console.log(this.differenceInObj(productPreviousCommand, model))
Output {description: "<p>hello</p>"}
If you are not getting output as expected. Can you please share your input and expected output?
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));

Comments

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),
    []
  );
}

2 Comments

It returns undefined
@SanJaisy : Please see the code snippet added.
0

You can create a TypeScript function to compare two objects and return their differences, including nested objects, by recursively traversing the objects and comparing their properties. Here's a sample implementation:

function getObjectDifferences(obj1: any, obj2: any): any {
  if (typeof obj1 !== 'object' || typeof obj2 !== 'object') {
    return obj1 !== obj2 ? [obj1, obj2] : undefined;
  }

  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);
  const uniqueKeys = new Set([...keys1, ...keys2]);

  const differences: any = {};

  for (const key of uniqueKeys) {
    const value1 = obj1[key];
    const value2 = obj2[key];

    if (typeof value1 === 'object' && typeof value2 === 'object') {
      const nestedDifferences = getObjectDifferences(value1, value2);
      if (nestedDifferences) {
        differences[key] = nestedDifferences;
      }
    } else if (value1 !== value2) {
      differences[key] = [value1, value2];
    }
  }

  return Object.keys(differences).length === 0 ? undefined : differences;
}

const obj1 = {
  name: 'John',
  age: 30,
  address: {
    city: 'New York',
    zip: '10001',
  },
};

const obj2 = {
  name: 'Jane',
  age: 28,
  address: {
    city: 'San Francisco',
    zip: '94101',
  },
};

const differences = getObjectDifferences(obj1, obj2);
console.log(differences);

Output

{
  "name": [
    "John",
    "Jane"
  ],
  "age": [
    30,
    28
  ],
  "address": {
    "city": [
      "New York",
      "San Francisco"
    ],
    "zip": [
      "10001",
      "94101"
    ]
  }
} 

This function getObjectDifferences takes two objects, recursively compares their properties, and returns an object representing the differences between them. If there are no differences, it returns undefined. The example provided compares two objects obj1 and obj2, including nested objects within them.

Remember that this implementation is a basic example, and you can further refine it to suit your specific needs and handle various data types and edge cases.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.