使用jQuery检查另一个对象的键中是否存在数组的某些值

时间:2017-05-25 17:48:52

标签: jquery arrays javascript-objects

我们有一个阵列&对象

getSelectedArrValue = ['firstName', 'lastName'];
getSelectedObjValue = {firstName: 'John', lastName: null, birthYear: 1980 };

getSelectedArrValue& getSelectedObjValue由其他一些事件生成,并根据事件动态更改。现在,我希望如果对象getSelectedArrValue中存在getSelectedObjValue的值,并且对象中的任何一个都是null,它将在控制台中显示哪一个为空;像这样的东西:

console.log('OOPS! ' + ____ + ' is null.');

所以,那些选定数据的输出:

OOPS! lastName is null.

因为,变量的值是连续生成的。动态地基于一些改变的状态(事件),这些可以发生:

getSelectedArrValue = ['firstName', 'lastName'];
getSelectedObjValue = {firstName: 'null', lastName: null, birthYear: 1985 };

输出:

OOPS! firstName is null.
OOPS! lastName is null.

更多例子:

getSelectedArrValue = ['firstName', 'lastName'];
getSelectedObjValue = {firstName: 'Mike', lastName: 'Hussy', birthYear: 1990 };

输出:

Everything is fine!

另一个例子:

getSelectedArrValue = ['phoneNumber', 'address'];
getSelectedObjValue = {firstName: 'Mike', lastName: 'Hussy', birthYear: 1990 };

输出:

Everything is fine! 

请帮助我编写jQuery代码来实现这些功能。我猜,js会是这样的:

for (var i = 0; i < getSelectedArrValue.length; i++) {
   if (getSelectedArrValue[i] in getSelectedObjValue.i) {
      // I am not sure that 'i' in object (getSelectedObjValue.i) works or not at here. 
      // Is there any other method to access value/key of object?
      if (getSelectedObjValue.i === null) {
         console.log('OOPS! ' + getSelectedArrValue[i] + ' is null.');
      } else {
         console.log('Everything is fine!');
      }
   }
}

但是,我不能以正确的方式编写,因为我在jQuery中不够好。这就是我寻求帮助的原因。提前谢谢!

1 个答案:

答案 0 :(得分:1)

对于每个数组值,您可以对对象使用hasOwnProperty检查,如下所示:

for (var i = 0; i < getSelectedArrValue.length; i++) {
      if (!getSelectedObjValue.hasOwnProperty(getSelectedArrValue[i]) || getSelectedObjValue[getSelectedArrValue[i]] === null) {
         console.log('OOPS! ' + getSelectedArrValue[i] + ' is null.');
      } else {
         console.log('Everything is fine!');
      }
}

编辑:如果您希望代码输出一切正常,以防对象在数组中没有属性,则需要修改if条件:

getSelectedObjValue.hasOwnProperty(getSelectedArrValue[i]) && getSelectedObjValue[getSelectedArrValue[i]] === null