如何检查一个对象是否存在于另一个对象中?

时间:2018-11-05 19:37:58

标签: javascript

使用下面的数组,其中包含两个对象,其中包含另一个对象,我想知道是否有一种方法可以找到哪个applicationID的申请人ID等于“ 5bd3480af09ddf0258c3a31d”

Array [
  Object {
    "__typename": "JobApplication",
    "_id": "5be097753397465946e051fd",
    "applicant": Object {
      "__typename": "User",
      "_id": "5bd83b9a62a9f33cf0f1033b",
    },
  },
  Object {
    "__typename": "JobApplication",
    "_id": "5bdc7c8b3241cb5bc10ac694",
    "applicant": Object {
      "__typename": "User",
      "_id": "5bd3480af09ddf0258c3a31d",
    },
  },
]

因此,在这种情况下,它必须返回“ 5bdc7c8b3241cb5bc10ac694”。

这是我的两个常量,第一个将返回用户ID,第二个将仅返回应用程序ID。

const { _id } = this.props.getMe.me._id;
const applicationID = getJobApplicationsForThisJob.map(application => application._id);

我可以检查用户ID是否在这样的对象中

const applicantId = getJobApplicationsForThisJob.map(user => user.applicant._id);
const hasApplied = applicantId.includes(_id);

谢谢

2 个答案:

答案 0 :(得分:2)

您可以使用.find方法。

var item = arr.find(function(x) {
  return x.applicant._id == find;
});

find方法返回找到的第一个项目,如果未找到记录,则返回undefined。

var arr = [{
  "__typename": "JobApplication",
  "_id": "5be097753397465946e051fd",
  "applicant": {
    "__typename": "User",
    "_id": "5bd83b9a62a9f33cf0f1033b",
  }
}, {
  "__typename": "JobApplication",
  "_id": "5bdc7c8b3241cb5bc10ac694",
  "applicant": {
    "__typename": "User",
    "_id": "5bd3480af09ddf0258c3a31d",
  },
}];

var find = "5bd3480af09ddf0258c3a31d";

var item = arr.find(function(x) {
  return x.applicant._id == find;
});


console.log(item != undefined ? item._id : "Not Found");

答案 1 :(得分:0)

由于您使用的是Javascript,因此您想要执行类似我的评论的操作

let _id = "5bd3480af09ddf0258c3a31d";
let list = [];  //your list of objects.
let applicationResults = list.where( (app) => app.applicant._id = _id);
if (applicationResults.length == 0){
  console.log("no applicantion with this applicant found.");
}else {
  console.log("Found " + applicationResults.length + " Applications from this Applicant")
  return applicationResults;
}