简体   繁体   English

Javascript:遍历包含对象的嵌套数组

[英]Javascript : loop through nested arrays that contain objects

I have a tow arrays that contain objects I want to compare to find unmatched values from the objects and return the object if contain unmatched value but I'm confused I get wrong value any help or idea it's my code 我有一个拖曳数组,其中包含一些对象,我想将它们进行比较以从对象中查找不匹配的值,如果包含不匹配的值,则返回该对象,但是我很困惑,我得到的错误帮助或想法都是我的代码错误

 var firstarry=[{'name':'alex','age':22,'numbersOne':['111','222','333','444','555'],'location':'iq'},{'name':'jan','age':33,'numbersOne':['111','222','333','444'],'location':'in'}]; var secondarray=[{'name':'aga','age':12,'numbersTwo':['111','222','333','444'],'location':'usa'},{'name':'jan','age':35,'numbersTwo':['111','222','333','444'],'location':'uk'}]; var un_mached_rows=[]; var tmp_recorder={}; firstarry.forEach(function(firstArrayElements){ if(firstArrayElements.hasOwnProperty('numbersOne')){ firstArrayElements.numbersOne.forEach(function(numberOneElements){ secondarray.forEach(function(secondArrayElements){ if(secondArrayElements.hasOwnProperty('numbersTwo')){ secondArrayElements.numbersTwo.forEach(function(numbersTwoElements){ if(numberOneElements!=numbersTwoElements){ tmp_recorder.name = firstArrayElements.name; tmp_recorder.age = firstArrayElements.age; tmp_recorder.location = firstArrayElements.location; tmp_recorder.numbers = numberOneElements; un_mached_rows.push(tmp_recorder); tmp_recorder; } }); } }); }); } }); console.log(un_mached_rows); 

it should return the un_mached_rows=[{'name':'alex','age':22,'numbers':'555'}] but now it return 56 wrong record 它应该返回un_mached_rows=[{'name':'alex','age':22,'numbers':'555'}]但现在返回56条错误记录

You have a pretty big logic error in your routine. 您的例程中有一个很大的逻辑错误。

You basically are comparing each element of the first array, with each element of the second array.... and even if the first array matches 1 element in the first array it won't match the rest so you get every other element of array 2 added to your results... IE: 您基本上是在将第一个数组的每个元素与第二个数组的每个元素进行比较....,即使第一个数组与第一个数组中的一个元素匹配,也不会与其余元素匹配,因此您可以获得数组的所有其他元素2添加到您的结果中... IE:

array1 = 1,2 array2 = 1,2,3 array1 = 1,2 array2 = 1,2,3

First outer loop value from array1 is 1.... array1的第一个外循环值为1。

Looping through array2 first time through the inner loop array2 element is 1 so 1=1 and they match.... so nothing is added to your result, however on loop 2 and 3 of the inner loop 1 will not match 2 or 3, so they are both added to the result array... 第一次通过内部循环array2元素循环通过array2是1,所以1 = 1且它们匹配...。因此没有添加任何结果,但是在内部循环1的循环2和3上将不匹配2或3,因此它们都被添加到结果数组中...

Then the outer loop value changes to 2 and you get the same behavior. 然后,外循环值更改为2,您将获得相同的行为。

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

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