我有两个对象数组,如下所示:
var array1 = [{"id": "-1","OwnerID": 777,"Admin": "true"},{"id": "-1","OwnerID": 555,"Admin": "true"},{"id": "-1","OwnerID": 444,"Admin": "true"},{"id": "-1","OwnerID": 222,"Admin": "true"},{"id": "-1","OwnerID": 111,"Admin": "true"}];
var array2 = [{"id": 777, "OwnerName": "Blah", "OwnerType": "Test"},{"id": 555, "OwnerName": "Blah", "OwnerType": "Test"},{"id": 444, "OwnerName": "Blah", "OwnerType": "BusinessMan"},{"id": 222, "OwnerName": "Blah", "OwnerType": "BusinessMan"},{"id": 111, "OwnerName": "Blah", "OwnerType": "BusinessMan"},{"id": 234, "OwnerName": "Blah", "OwnerType": "BusinessMan"},{"id": 432, "OwnerName": "Blah", "OwnerType": "Test"},{"id": 112, "OwnerName": "Blah", "OwnerType": "BusinessMan"},{"id": 114, "OwnerName": "Blah", "OwnerType": "Test"}]
我需要获取array1的过滤数组,其中array2中的OwnerType为Test。 array1中的OwnerID链接到数组2中的id。我希望尽可能少地执行此操作。理想情况下,我主要想查看数组长度是否大于1,因为第一个数组应该只有一个类型。任何帮助表示赞赏。
编辑:
所需的输出应该是array1,如下所示:
[{"id": "-1","OwnerID": 777,"Admin": "true"},{"id": "-1","OwnerID": 555,"Admin": "true"}]
答案 0 :(得分:0)
两个嵌套循环应该很容易解决:
var array_result = [];
for(var i = 0; i < array1.length; i++){
for(var j = 0; j < array2.length; j++){
if(array2[j].id == array1[i].OwnerID && array2[j].OwnerType == "Test")
array_result.push(array1[i]);
}
}
如果array2是一个关联数组,将id作为键,那么过滤的复杂性就会大大降低。
答案 1 :(得分:0)
首先,您要返回array2
中具有匹配id
(array1
)和OwnerID
(array2
)值的所有对象。
// array of `OwnerID` values
var idArr = array1.map(function(obj) { return obj.OwnerID; });
然后,您只获得来自array2
的具有匹配id
(array1
OwnerID
且OwnerType
Test
的对象}。
// filter array2 by matches
var matches = array2.map(function(obj) {
return idArr.indexOf(obj.id) > -1 && obj.OwnerType === 'Test';
});
结果matches
将是一个具有正确id
和OwnerType
Test
的对象数组。
答案 2 :(得分:0)
答案我最终使用
array1.filter(ar1 => array2.filter(ar2 => ar2.OwnerType == 'Test' && ar2.id == ar1.OwnerID).length > 0).length > 1
感谢大家的帮助