[英]Javascript Compare two arrays with different sizes and return the items that are not in second array
[英]Angular - Compare two arrays with same number of objects but with different values and return the difference from second array
我有 2 个对象数组
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'}]
正如我们在arrayTwo
中看到的, objectName
和dataType
发生了变化。 任何属性都可能发生变化,但 arrays 上的对象数量将始终相同。
所以在这里,我需要从arrayTwo
中提取已通过与arrayOne
进行比较而更改的对象,并将其存储在一个新的数组中,比如resultsArray
?
我检查了如何获取 JavaScript 中对象的两个 arrays 之间的差异中提供的答案,它只讨论基于一个属性而不是任何属性获取差异。 请就此提出建议。 谢谢。
编辑:编辑arrayTwo
为objectType
有大写字母。 我需要忽略大小写,结果应该不区分大小写。 谢谢
一种选择是遍历第一个数组元素,通过其 id 找到第二个数组的相同元素,然后检查其任何属性是否已更改:
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);
编辑:上面的示例将返回 arrayOne 中的元素。 如果您需要具有新值的元素,您可以在 function 中反转 arrayOne 和 arrayTwo。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.