查找是否有任何数组条目与对象属性匹配

时间:2016-10-28 12:10:35

标签: javascript arrays object lodash

我有一个数组:

 arr=[
      "EMPRESA",
      "CD_DIRECAO",
      "DT_INI_DIRECAO"
    ]

我有一个对象:

primary = {
           "EMPRESA": {"type": "varchar"},
           "CD_DIRECAO": {"type": "varchar"},
           "DT_INI_DIRECAO": {"type": "date"},
           "CD_DEPT": {"type": "varchar"},
           "DT_INI_DEPT": {"type": "date"},
           "ANO": {"type": "number"},
           "MES": {"type": "number"},
           "TP_CUSTO": {"type": "varchar"},
          }

我需要检查主要中是否存在至少一个arr元素。 Apreciate你的帮助。

4 个答案:

答案 0 :(得分:2)

您可以使用Array#some进行迭代,并检查密钥是否存在。

var arr = ["EMPRESA", "CD_DIRECAO", "DT_INI_DIRECAO"],
    primary = { EMPRESA: { type: "varchar"}, CD_DIRECAO: { type: "varchar"}, DT_INI_DIRECAO: { type: "date"}, CD_DEPT: { type : "varchar"}, DT_INI_DEPT: { type: "date"}, ANO: { type: "number"},  MES: { type: "number"}, TP_CUSTO: { type: "varchar"}},
    contain = arr.some(function (k) {
        return k in primary;
    });

console.log(contain);

答案 1 :(得分:1)

您可以迭代对象的键并使用indexOf检查是否退出:

for (property in primary){
       if (arr.indexOf(property) !== -1)
         console.log("Exists");
 };

使用Object.keys

Object.keys(primary, function(key){
    if (arr.indexOf(key) !== -1)
        console.log("Exists"); 
});

答案 2 :(得分:1)

for (var i = 0; i< arr.length; i++){
    if (primary[arr[i]]){
        //exists
    }
}

答案 3 :(得分:1)

使用Array.prototype.some的答案:

var arr=["EMPRESA","CD_DIRECAO","DT_INI_DIRECAO"];
var primary={EMPRESA:{type:"varchar"},CD_DIRECAO:{type:"varchar"},DT_INI_DIRECAO:{type:"date"},CD_DEPT:{type:"varchar"},DT_INI_DEPT:{type:"date"},ANO:{type:"number"},MES:{type:"number"},TP_CUSTO:{type:"varchar"}};

var result = arr.some(function(element){
   return primary[element];
});

console.log(result);