为什么_.difference会返回所有项目?

时间:2016-01-29 02:48:14

标签: javascript lodash

我有两个列表,oldPanodatasnewPanodatas。我想只获取newPanodatasoldPanodatas中不存在的var filteredPanodatas = _.difference(newPanodatas, oldPanodatas) 中的对象。我这样做了:

_.difference

但是我收到了所有项目,OLD: Object {roomModelId: "56a9e0088ac247005538d6d3", x: 262, index: 1, y: 211, panoDataRotate: 0…} OLD: Object {roomModelId: "56a9e0088ac247005538d6d3", x: 177, index: 0, y: 182, panoDataRotate: 0…} NEW: Object {index: 0, x: 177, y: 182, roomModelId: "56a9e0088ac247005538d6d3", panoDataRotate: 0} NEW: Object {index: 1, x: 262, y: 211, roomModelId: "56a9e0088ac247005538d6d3", panoDataRotate: 0} NEW: Object {index: 2, x: 200, y: 200, roomModelId: "56a9e0088ac247005538d6d3", panoDataRotate: 0} FILTERED: Object {index: 0, x: 177, y: 182, roomModelId: "56a9e0088ac247005538d6d3", panoDataRotate: 0} FILTERED: Object {index: 1, x: 262, y: 211, roomModelId: "56a9e0088ac247005538d6d3", panoDataRotate: 0} FILTERED: Object {index: 2, x: 200, y: 200, roomModelId: "56a9e0088ac247005538d6d3", panoDataRotate: 0} 并未过滤任何内容:

{{1}}

这是为什么?什么是实现我想要的正确方法?

1 个答案:

答案 0 :(得分:1)

尝试使用differceWith,调用isEqual比较器,将数组元素与值进行比较

_.differenceWith(newPanodatas, oldPanodatas, _.isEqual);

代码示例,

var old = [{roomModelId: "56a9e0088ac247005538d6d3", x: 262, index: 1, y: 211, panoDataRotate: 0},  {roomModelId: "56a9e0088ac247005538d6d3", x: 177, index: 0, y: 182, panoDataRotate: 0}];
newobj = [{index: 0, x: 177, y: 182, roomModelId: "56a9e0088ac247005538d6d3", panoDataRotate: 0}, {index: 1, x: 262, y: 211, roomModelId: "56a9e0088ac247005538d6d3", panoDataRotate: 0}, {index: 2, x: 200, y: 200, roomModelId: "56a9e0088ac247005538d6d3", panoDataRotate: 0}];
r = _.differenceWith(newobj, old, _.isEqual);

r

的结果
[{index: 2, panoDataRotate: 0, roomModelId: "56a9e0088ac247005538d6d3", x: 200, y: 200}]