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

时间:2016-11-08 19:32:26

标签: javascript arrays object underscore.js

我有以下数组

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"

我也有像这样的对象数组。

data = ["004"];

如您所见,带有004的id包含数组和对象。我想检查对象'Results'中数组'data'中有多少元素。

最终结果应为

cordova emulate ios --list

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

3 个答案:

答案 0 :(得分:1)

没有下划线.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);
&#13;
&#13;
&#13;

使用underscore.js

&#13;
&#13;
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);
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我想以下代码(未经过测试)

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

答案 2 :(得分:0)

这可以为您提供所需的信息。

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"]