循环遍历一个对象和一个循环遍历数组的嵌套for循环

Looping through an object and a nested for loop that loops through array

我正在遍历一个对象,然后在每个对象上将它与我的数组中的项目进行比较,希望随后将不相同的对象推送到我的 ItemsNotInObject 数组中。希望有人能为我阐明这一点。提前谢谢你。

var obj = {a:1, a:2, a:3};
var array = [1, 4, 2, 5, 6];
var ItemsNotInObject = [];


for (var prop in obj) {
    for(var i = 0, al = array.length; i < al; i++){
       if( obj[prop].a !== array[i] ){
           ItemsNotInObject.push(array[i]);
        }
    }
}

console.log(ItemsNotInObject);
//output of array: 1 , 4 , 2 , 5, 6

//output desired is: 4 , 5 , 6

如果你可以让你的 obj 变量成为一个数组,你可以这样做;

var obj = [1, 2, 3];
var array = [1, 4, 2, 5, 6];
var ItemsNotInObject = [];


    for(i in array){
       if( obj.indexOf(array[i]) < 0) ItemsNotInObject.push(array[i]);
    }

console.log(ItemsNotInObject);

如果 obj 变量需要是 json 对象,请提供它的正确形式,以便我可以根据它更改代码。

  1. 您的对象有重复键。这 不是有效的 JSON 对象。让它们独一无二
  2. 不要访问像obj[prop].aobj[prop] is a
  3. 这样的对象值
  4. 克隆原始数组。
  5. 使用indexOf()检查数组是否包含对象属性。
  6. 如果是,请将其从克隆阵列中删除。

var obj = {
  a: 1,
  b: 2,
  c: 3
};
var array = [1, 4, 2, 5, 6];
var ItemsNotInObject = array.slice(); //clone the array

for (var prop in obj) {
  if (array.indexOf(obj[prop]) != -1) {
    for (var i = 0; i < ItemsNotInObject.length; i++) {
      if (ItemsNotInObject[i] == obj[prop]) {
        ItemsNotInObject.splice(i, 1); //now simply remove it because it exists
      }
    }
  }
}

console.log(ItemsNotInObject);