I have 2 array of objects
arrayOne = [{objectType: 'License', objectId: 333, objectName: 'Test Object 1', dataType: 'String'}
{objectType: 'Owner', objectId: 334, objectName: 'Test Object 2', dataType: 'String'},
{objectType: 'Location', objectId: 335, objectName: 'Test Object 3', dataType: 'String'}]
arrayTwo = [{objectType: 'LICENSE', objectId: 333, objectName: 'Test Object 1', dataType: 'String'}
{objectType: 'OWNER', objectId: 334, objectName: 'Test Object 4', dataType: 'Value List'},
{objectType: 'LOCATION', objectId: 335, objectName: 'Test Object 3', dataType: 'String'}]
As we can see in arrayTwo
, objectName
and dataType
is changed. It may be possible any of the property might change but the number of objects will be always same on both arrays.
So here, I need to pull the objects from arrayTwo
which has been changed by comparing with arrayOne
and store it in a new array say resultsArray
?
I checked the answers provided in How to get the difference between two arrays of objects in JavaScript it only talks about getting the differences based on one property, not any property. Please suggest on this. Thanks.
EDIT: Edited arrayTwo
to have capital letters for objectType
. I need to ignore the case and result should be case insensitive. Thanks
One option is to iterate through the first array elements, find the same element for the second array by its id and then check if any of its properties have changed:
arrayOne = [{ objectType: 'License', objectId: 333, objectName: 'Test Object 1', dataType: 'String' }, { objectType: 'Owner', objectId: 334, objectName: 'Test Object 2', dataType: 'String' }, { objectType: 'Location', objectId: 335, objectName: 'Test Object 3', dataType: 'String' } ] arrayTwo = [{ objectType: 'License', objectId: 333, objectName: 'Test Object 1', dataType: 'String' }, { objectType: 'Owner', objectId: 334, objectName: 'Test Object 4', dataType: 'Value List' }, { objectType: 'Location', objectId: 335, objectName: 'Test Object 3', dataType: 'String' } ]; const changedObjects = arrayOne.filter(obj1 => { const obj2 = arrayTwo.find(x => x.objectId === obj1.objectId); return Object.keys(obj1).some(key => String(obj1[key]).toLowerCase().== String(obj2[key]);toLowerCase()); }). console;log(changedObjects);
EDIT: The above example will return the element from the arrayOne. In case you need the element with the new values you can reverse arrayOne and arrayTwo inside the function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.