检查对象数组中是否存在数组列表

Check if list of array exists in the array of objects

我有以下数组

var data  = ["004", "456", "333", "555"];

我也有一个这样的对象数组。

Object {Results:Array[2]}
Results:Array[2]
    [0-1]
         0:Object
           id="004"     
           name: "Rick"
           Active: "false"
         1:Object
           id="005"     
           name:'david'
           Active: "false"

如你所见,004的id既存在于数组中,也存在于对象中。我想检查对象“结果”中存在数组 'data' 中的多少个元素。

最终结果应该是

data = ["004"];

任何人都可以告诉我如何搜索这个

我猜如下代码(未测试)

l_return = [];
for (l_cnt = 0; l_cnt < Results.length - 1; l_cnt++) {
    if (data.indexof(Result[l_cnt].id) != -1) l_return.push(Result[l_cnt].id)
}
data = l_return

没有underscore.js

var data = ["004", "456", "333", "555"];
arr = [{
  id: "004",
  name: "Rick",
  Active: "false"
}, {
  id: "005",
  name: 'david',
  Active: "false"
}];

out = [];
for (var i = 0; i < arr.length; i++) {
  for (var j = 0; j < data.length; j++) {
    if (arr[i].id === data[j])
      out.push(data[j]);
  }
}
console.log(out);

和underscore.js

var data = ["004", "456", "333", "555"];
arr = [{
  id: "004",
  name: "Rick",
  Active: "false"
}, {
  id: "005",
  name: 'david',
  Active: "false"
}];

out = [];

_.each(arr, function(value1, key1, obj1) {
  _.each(data, function(value, key, obj) {
    if (value1.id == value) out.push(value);
  });
});

console.log(out);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://underscorejs.org/underscore-min.js"></script>

这应该能满足您的需求。

var data  = ["004", "456", "333", "555"];
var results = [
  {
    id: "004",
    name: "Rick",
    Active: "false"
  },{
    id: "005",
    name: "david",
    Active: "false"
  }
];


var found = [];
results.forEach(i => {
  if(data.includes(i.id)){
    if(!found.includes(i.id)) found.push(i.id);
  }
});

console.log(found) // ["004"]