น่าเสียดายที่ฉันไม่มี JQuery หรือ Underscore มีแค่ javascript ล้วน ๆ (เข้ากันได้กับ IE9)
ฉันต้องการเทียบเท่ากับ SelectMany () จากฟังก์ชัน LINQ
// SelectMany flattens it to just a list of phone numbers.
IEnumerable<PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);
ฉันทำมันได้ไหม?
แก้ไข:
ขอบคุณสำหรับคำตอบฉันได้ผล:
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