How to do equivalent of LINQ SelectMany() just in javascript

后端 未结 9 1449
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 16:54

Unfortunately, I don\'t have JQuery or Underscore, just pure javascript (IE9 compatible).

I\'m wanting the equivalent of SelectMany() from LINQ functionality.

<
9条回答
  •  一整个雨季
    2020-12-13 17:36

    Sagi is correct in using the concat method to flatten an array. But to get something similar to this example, you would also need a map for the select part https://msdn.microsoft.com/library/bb534336(v=vs.100).aspx

    /* arr is something like this from the example PetOwner[] petOwners = 
                        { new PetOwner { Name="Higa, Sidney", 
                              Pets = new List{ "Scruffy", "Sam" } },
                          new PetOwner { Name="Ashkenazi, Ronen", 
                              Pets = new List{ "Walker", "Sugar" } },
                          new PetOwner { Name="Price, Vernette", 
                              Pets = new List{ "Scratches", "Diesel" } } }; */
    
    function property(key){return function(x){return x[key];}}
    function flatten(a,b){return a.concat(b);}
    
    arr.map(property("pets")).reduce(flatten,[])
    

提交回复
热议问题