如何只在javascript中做LINQ SelectMany()的等效项 [英] How to do equivalent of LINQ SelectMany() just in javascript

查看:57
本文介绍了如何只在javascript中做LINQ SelectMany()的等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不幸的是,我没有JQuery或Underscore,只有纯JavaScript(与IE9兼容)。

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

我想要LINQ功能的SelectMany()

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

// SelectMany flattens it to just a list of phone numbers.
IEnumerable<PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);

我可以吗?

编辑:

感谢答案,我可以正常工作:

Thanks to answers, I got this working:

var petOwners = 
[
    {
        Name: "Higa, Sidney", Pets: ["Scruffy", "Sam"]
    },
    {
        Name: "Ashkenazi, Ronen", Pets: ["Walker", "Sugar"]
    },
    {
        Name: "Price, Vernette", Pets: ["Scratches", "Diesel"]
    },
];

function property(key){return function(x){return x[key];}}
function flatten(a,b){return a.concat(b);}

var allPets = petOwners.map(property("Pets")).reduce(flatten,[]);

console.log(petOwners[0].Pets[0]);
console.log(allPets.length); // 6

var allPets2 = petOwners.map(function(p){ return p.Pets; }).reduce(function(a, b){ return a.concat(b); },[]); // all in one line

console.log(allPets2.length); // 6


推荐答案

对于简单的选择,您可以使用

假设您有一个数字数组:

for a simple select you can use the reduce function of Array.
Lets say you have an array of arrays of numbers:

var arr = [[1,2],[3, 4]];
arr.reduce(function(a, b){ return a.concat(b); });
=>  [1,2,3,4]

var arr = [{ name: "name1", phoneNumbers : [5551111, 5552222]},{ name: "name2",phoneNumbers : [5553333] }];
arr.map(function(p){ return p.phoneNumbers; })
   .reduce(function(a, b){ return a.concat(b); })
=>  [5551111, 5552222, 5553333]

编辑:

,因为es6 flatMap已添加到Array原型中。
SelectMany flatMap 的同义词。

该方法首先映射每个元素使用映射函数,然后将结果展平为新数组。
在TypeScript中的简化签名为:


since es6 flatMap has been added to the Array prototype. SelectMany is synonym to flatMap.
The method first maps each element using a mapping function, then flattens the result into a new array. Its simplified signature in TypeScript is:

function flatMap<A, B>(f: (value: A) => B[]): B[]

为了完成任务,我们只需要flatMap将每个元素映射到phoneNumbers

In order to achieve the task we just need to flatMap each element to phoneNumbers

arr.flatMap(a => a.phoneNumbers);

这篇关于如何只在javascript中做LINQ SelectMany()的等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆