简体   繁体   English

使用“ forEach”的嵌套循环遍历流星中的一个集合

[英]iterate over a collection in meteor using nested loop of “ forEach ”

I will start with a small description of the result I want to get: 我将从对要获得的结果的简短描述开始:

Let's imagine we have a collection called " Elements " which contains the 4 documents: 'a','b','c' and 'd'. 假设我们有一个名为“ Elements ”的集合,其中包含4个文档:“ a”,“ b”,“ c”和“ d”。 I want to iterate over " Elements " and insert in a new collection called " Queries " the pairs : 我想遍历“ Elements ”并在一个名为“ Queries ”的新集合中插入对:

(a,b);(a,c);(a,d);(b,a);(b,c)...(d,a);(d,b);(d,c). (A,B);(A,C);(一,d);(B,A);(B,C)...(d,A);(d,B);(d,C)。 => which means " Queries " will contain (in this example) 4*3 = 12 pairs of elements (documents) at the end. =>,这意味着“ 查询 ”将在此示例的末尾包含4 * 3 = 12对元素(文档)。

Here is the code I'm using (it's a method in meteor server triggered by a click on a button): 这是我正在使用的代码(这是流星服务器中通过单击按钮触发的一种方法):

'Queries': function() {
    var allElements = Elements.find();
    allElements.forEach(function(myLeftElement){ //First forEach
        allElements.forEach(function(myRightElement){// Nested forEach
            if(myLeftElement._id !== myRightElement._id){
                Queries.insert( {myLeftElement : myLeftElement._id, myRightElement : myRightElement._id} );
            }
        }); //End Of nested forEach
    }); //End Of First forEach
}

In fact it works only for the first "myLeftElement" with all other elements "myRightElement" but stops there: it inserts, into "Queries" collection, the pairs: [(a,b);(a,c) and (a,d)] and then stops. 实际上,它仅适用于第一个“ myLeftElement”以及所有其他元素“ myRightElement”,但在此停止:它将对[[a,b);(a,c)和(a, d)],然后停止。

Since I am a beginner in web developement in general and in using Meteor in particular, I am seeking for your help. 由于我一般是Web开发的初学者,尤其是使用Meteor的初学者,因此我正在寻求您的帮助。

1) I need to understand why once the nested cursor method "forEach" stops, the whole function stops. 1)我需要了解为什么一旦嵌套光标方法“ forEach”停止,整个函数就会停止。

2) How can I improve the code to get the result I really want: to every element of my collection "myLeftElement" there is a forEach method that creates pairs with all other elements "myRightElement". 2)如何改进代码以获得我真正想要的结果:对于我的集合“ myLeftElement”的每个元素,都有一个forEach方法,该方法与所有其他元素“ myRightElement”创建对。 And then moves to the next "myLeftElement" and do the same till the end. 然后移至下一个“ myLeftElement”并执行相同操作直至结束。

Thanks, 谢谢,

Here is a working example of iterating over an Array with vanilla JavaScript that gets the expected result: 这是一个使用香草JavaScript迭代数组以获取预期结果的工作示例:

 var elements = ['a', 'b', 'c', 'd']; var result = []; elements.forEach(function(item) { // Create a copy of the current array to work with var elements_copy = elements.slice(0); var temp_array = []; /* Delete the current `item` from the array since we don't want duplicate 'a:a' items in the array. IMPORTANT: There are better ways of doing this, see: http://stackoverflow.com/questions/3954438/remove-item-from-array-by-value */ elements_copy.splice(elements_copy.indexOf(item), 1); elements_copy.forEach(function(child_item) { temp_array.push(item + "," + child_item); }); result.push(temp_array); }); console.log(result); 

You'll need to make sure you open the Console in the Developer Tools to see the result. 您需要确保在开发人员工具中打开控制台才能看到结果。

When you're starting out I recommend getting working scenarios with the least complexity -- like here where I removed Meteor and Mongo out of the picture -- to ensure that your logic is sound then working in the rest from there. 当您刚开始时,我建议您以最低的复杂度来进行工作,例如在这里我从图中删除了Meteor和Mongo,以确保您的逻辑是合理的,然后再从那里进行其他工作。

So, to answer your questions directly: 因此,直接回答您的问题:

  1. Unsure of why it is stopping as I'm unable to recreate 不确定为什么停止,因为我无法重新创建
  2. Example provided should suffice -- but I'm sure there is a better way 提供的示例就足够了-但我敢肯定有更好的方法

Hope that helps! 希望有帮助!

The @cynicaljoy's answer inspired me in two ways: @cynicaljoy的回答从两个方面启发了我:

  • using arrays 使用数组
  • and a better way of deleting duplicate 'a:a' items in the arrays (by visiting the link he provided). 以及删除数组中重复的“ a:a”项的更好方法(通过访问他提供的链接)。

So thanks a lot. 非常感谢。

Now after taking the necessary modifications, here is one solution that actually works fine using Meteor and Mongodb codes: 现在,在进行了必要的修改之后,这是一种使用Meteor和Mongodb代码实际上可以正常工作的解决方案:

'Queries' : function() {

var allElements = Elements.find().map(function(item){return item._id} ); /* this returns an array of item._id of all elements*/
var totalItems = allElements.length;
var itemsCounter = 0;
var withoutLeftItem;
   while(itemsCounter < totalItems){
      withoutLeftItem=_.without(allElements,allElements[itemsCounter] ); /*The function _.without(array, *items) used in underscore.js returns array with specified items removed */    
      withoutLeftItem.forEach(function(myRightElement){
         Queries.insert( {myLeftElement : allElements[itemsCounter], myRightElement : myRightElement} );
      });
   itemsCounter++;
   }
 }

I am still curious to understand why the solution presented in the question was not working as it was supposed and also to see an optimized code in terms of memory usage. 我仍然很好奇要理解为什么问题中提出的解决方案无法按预期工作,并且还希望看到有关内存使用情况的优化代码。

Hope this helps other people. 希望这对其他人有帮助。 Thanks all 谢谢大家

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

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