我正在寻找一种方法,根据该对象的属性查找一个数组中不存在于另一个数组中的任何对象。使用 jQuery 或下划线执行此操作的最佳方法是什么?
给出以下示例:
"array1":[
{"testProperty":"A"},
{"testProperty":"B"},
{"testProperty":"C"}
]
"array2":[
{"testProperty":"A", "User":"Smith"},
{"testProperty":"B", "User":"Smith"},
]
我想从 array1 返回第三个对象,其 testProperty 为“C”,因为它不存在于 array2 中。
我能够在 stackoverflow 上找到此问题的几个示例,但在需要使用这些对象的属性时却找不到。
最佳答案
我不确定这是否重要,但是如果您可以使用 lodash 而不是下划线,那么有一个很好的函数叫做 DifferenceBy:
var _ = require("lodash");
var array1 = [
{"testProperty":"A"},
{"testProperty":"B"},
{"testProperty":"C"}
]
var array2 = [
{"testProperty":"A", "User":"Smith"},
{"testProperty":"B", "User":"Smith"}
]
var result = _.differenceBy(array1, array2, function(item) {
return item["testProperty"]
});
console.log(result);
关于javascript - 通过属性查找一个数组中不存在于另一个数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37148913/