简体   繁体   English

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

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

I am looping through an object and then upon each object I am comparing it to the items in my array in hopes to then push the objects that are not the same into my ItemsNotInObject array. 我正在遍历一个对象,然后在每个对象上将其与数组中的项目进行比较,以期将不相同的对象推送到我的ItemsNotInObject数组中。 Hopefully someone can shine some light on this for me. 希望有人可以为我照亮一点。 Thank you in advance. 先感谢您。

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

If you can make your obj variable an array, you can do it this way; 如果可以将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);

if the obj variable needs to be json object please provide the proper form of it so i can change the code according to that. 如果obj变量需要是json对象,请提供它的正确形式,以便我可以根据它更改代码。

  1. Your object has duplicate keys. 您的对象具有重复的键。 This is not a valid JSON object. 不是有效的 JSON对象。 Make them unique 使它们独特
  2. Do not access the object value like obj[prop].a , obj[prop] is a 不要访问obj[prop].a类的对象值, obj[prop] a
  3. Clone the original array. 克隆原始数组。
  4. Use indexOf() to check if the array contains the object property or not. 使用indexOf()检查数组是否包含对象属性。
  5. If it does, remove it from the cloned array. 如果是这样,请将其从克隆的阵列中删除。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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