我有以下密钥数组:
var keys = [{userId: "333"}, {userId: "334"}]
这个对象数组:
var users = [
{id: "333", firstName: "", lastName: "", idCard: "", birthDate: ""},
{id: "334", firstName: "", lastName: "", idCard: "", birthDate: ""},
{id: "335", firstName: "", lastName: "", idCard: "", birthDate: ""},
{id: "336", firstName: "", lastName: "", idCard: "", birthDate: ""}
]
我需要通过使用users Array
[反向结果]对其进行过滤来更改我的keys Array
。
不能弄明白,得到所有的答案! (js,jquery,angular)
任何?
答案 0 :(得分:1)
您可以使用filter()
和find()
。
var users = [
{id: "333", firstName: "", lastName: "", idCard: "", birthDate: ""},
{id: "334", firstName: "", lastName: "", idCard: "", birthDate: ""},
{id: "335", firstName: "", lastName: "", idCard: "", birthDate: ""},
{id: "336", firstName: "", lastName: "", idCard: "", birthDate: ""}
]
var keys = [{userId: "333"}, {userId: "334"}]
var result = users.filter(function(o) {
return !keys.find(function(e) {
return e.userId == o.id
})
})
console.log(result)
答案 1 :(得分:1)
您可以拥有id
的数组,然后您可以在此列表中查看可用性
var users = [
{id: "333", firstName: "", lastName: "", idCard: "", birthDate: ""},
{id: "334", firstName: "", lastName: "", idCard: "", birthDate: ""},
{id: "335", firstName: "", lastName: "", idCard: "", birthDate: ""},
{id: "336", firstName: "", lastName: "", idCard: "", birthDate: ""}
]
var keys = [{userId: "333"}, {userId: "334"}]
var idList = keys.map(function(x){ return x.userId});
var r = users.filter(function(x){
return idList.indexOf(x.id) < 0
})
console.log(r)
&#13;
答案 2 :(得分:1)
您可以使用哈希表进行过滤。
var keys = [{ userId: "333" }, { userId: "334" }],
users = [{ id: "333", firstName: "", lastName: "", idCard: "", birthDate: "" }, { id: "334", firstName: "", lastName: "", idCard: "", birthDate: "" }, { id: "335", firstName: "", lastName: "", idCard: "", birthDate: "" }, { id: "336", firstName: "", lastName: "", idCard: "", birthDate: "" }],
filtered = users.filter(function (a) {
return !this[a.id];
}, keys.reduce(function (r, a) {
r[a.userId] = true;
return r;
}, Object.create(null)));
console.log(filtered);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;