如何通过 json 对象的选项卡中的 Id 检查对象是否存在?

How to check if object exist by Id in tab of json object?

我有一个对象数组:

 var tab =  [
   {
     "id": "1",
     "data" : "blabla" 
   },
   {
      "id": "2",
      "data": "samplesample"
   }
 ]

是否有任何简单的工具可以通过 id 检查此数组中是否存在对象。

类似于:

 chekexists(tab, "id", "1") ;  // return true
 chekexists(tab, "id", "2") ;  // return true
 chekexists(tab, "id", "3") ;  // return false
 chekexists(tab, "data", "blabla") ;  // return true
 chekexists(tab, "data", "toto") ;  // return false

是否可以用下划线执行此操作?

为了避免混淆,我的标签是这样加载的:

var tab = JSON.parse(fs.readFileSync('path'));

您可以使用 _.findWhere:

function checkexists(list, props) {
  return _.findWhere(list, props) !== undefined;
}

checkexists(tab, {id: 1});
checkexists(tab, {data: 'toto'});

您可以像下面这样使用下划线:

function checkexists(array, prop) {
  return !!_.where(array, prop).length;
}

现在您可以像这样使用它:

checkexists(tab, {id: '1'});
checkexists(tab , "data", "blabla") ;  

轻松使用开源项目jinqJs

var tab =  [
   {
     "id": "1",
     "data" : "blabla" 
   },
   {
      "id": "2",
      "data": "samplesample"
   }
 ]
 
var result = jinqJs().from(tab).where('id == 2').select();

document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre><br><br>';

//OR you can do this
result = jinqJs().from(tab).in(['1','2'], 'id').select();
document.body.innerHTML += '<pre>' + JSON.stringify(result, null, 4) + '</pre><br><br>';
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.js"></script>