我有两个对象数组,我想通过identifier
查找newData和oldData数组之间的区别,显示区别,其中oldData的标识符与newData数组不同,这是我的数组:
const newData = [
{
"extras": {},
"identifier": "13",
"latitude": 39.13063,
"loiteringDelay": 1000,
"longitude": -86.58286,
"notifyOnDwell": false,
"notifyOnEntry": true,
"notifyOnExit": true,
"radius": 30,
},
{
"extras": {},
"identifier": "18",
"latitude": 39.13063,
"loiteringDelay": 1000,
"longitude": -86.58286,
"notifyOnDwell": false,
"notifyOnEntry": true,
"notifyOnExit": true,
"radius": 30,
}
]
const oldData = [
{
"identifier": "13",
"latitude": 39.13063,
"loiteringDelay": 1000,
"longitude": -86.58286,
"notifyOnDwell": false,
"notifyOnEntry": true,
"notifyOnExit": true,
"radius": 30,
},
{
"identifier": "12",
"latitude": 39.13063,
"loiteringDelay": 1000,
"longitude": -86.58286,
"notifyOnDwell": false,
"notifyOnEntry": true,
"notifyOnExit": true,
"radius": 30,
}
]
这是我在做什么:
let testDifference = _.differenceBy(newData, oldData, "identifier")
我的期望是,我会得到
[
{
"identifier": "12",
"latitude": 39.13063,
"loiteringDelay": 1000,
"longitude": -86.58286,
"notifyOnDwell": false,
"notifyOnEntry": true,
"notifyOnExit": true,
"radius": 30,
},
]
实际上,我得到的是空数组,我做错了什么?如何使其正常工作?
最佳答案
我认为您只需要将前两个参数切换到differenceBy
即可获得期望的结果。您可以将其视为第二个数组项以外的第一个数组项。
const newData = [{
"extras": {},
"identifier": "13",
"latitude": 39.13063,
"loiteringDelay": 1000,
"longitude": -86.58286,
"notifyOnDwell": false,
"notifyOnEntry": true,
"notifyOnExit": true,
"radius": 30,
}]
const oldData = [{
"identifier": "13",
"latitude": 39.13063,
"loiteringDelay": 1000,
"longitude": -86.58286,
"notifyOnDwell": false,
"notifyOnEntry": true,
"notifyOnExit": true,
"radius": 30,
},
{
"identifier": "12",
"latitude": 39.13063,
"loiteringDelay": 1000,
"longitude": -86.58286,
"notifyOnDwell": false,
"notifyOnEntry": true,
"notifyOnExit": true,
"radius": 30,
}
];
let whatDelete = _.differenceBy(oldData, newData, "identifier");
console.log(whatDelete);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>