如何检查所有特定对象在数组中是否具有相同的值?

时间:2018-05-21 12:08:50

标签: javascript

我有一个像这样的JS对象:

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

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

我花了几个小时找到任何可能重复的问题,但还没找到,

如果var a为真且returnTKRRevision4,如何处理?

2 个答案:

答案 0 :(得分:2)

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);

答案 1 :(得分:1)

您可以通过传递回调函数作为参数来使用every方法,该函数适用于给定数组中的每个项目。



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);