简体   繁体   中英

How to check if all specific object has a same value in array?

I have an example JS Object like this:

var a = [
  {
    "Procedure_Code": "TKRRevision4",
  },
  {
    "Procedure_Code": "TKRRevision4",
  },
  {
    "Procedure_Code": "TKRRevision4",
  },
]

var b = [
  {
    "Procedure_Code": "TKRRevision4",
  },
  {
    "Procedure_Code": "TKRRevision3",
  },
  {
    "Procedure_Code": "TKRRevision4",
  },
]

I've spent a couple hours to find any possible duplicated question, but not find it yet,

How to handle if var a is true and return ing TKRRevision4 ?

 var a = [{ "Procedure_Code": "TKRRevision4", }, { "Procedure_Code": "TKRRevision4", }, { "Procedure_Code": "TKRRevision4", }, ] var b = [{ "Procedure_Code": "TKRRevision4", }, { "Procedure_Code": "TKRRevision3", }, { "Procedure_Code": "TKRRevision4", }, ] function checkValue(response) { var c = a.every(val => val.Procedure_Code == response.key) var d = b.every(val => val.Procedure_Code == response.key) return { a: c, b: d }; } var apiResponse = { key: "TKRRevision4" }; var validation = checkValue(apiResponse); console.log("a => " + validation.a); console.log("b => " + validation.b); 

You can use every method by passing a callback function as argument which is applied for every item from your given array.

 var a = [ { "Procedure_Code": "TKRRevision4", }, { "Procedure_Code": "TKRRevision4", }, { "Procedure_Code": "TKRRevision4", }, ] var b = [ { "Procedure_Code": "TKRRevision4", }, { "Procedure_Code": "TKRRevision3", }, { "Procedure_Code": "TKRRevision4", }, ] function check(array){ let first_obj = array[0]; return array.every( elem => Object .keys(elem) .every(key => elem[key] == first_obj[key])); } let result_a = check(a); let result_b = check(b); console.log(result_a); console.log(result_b); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM