Javascript数组中的连接和聚合

时间:2013-02-23 18:20:07

标签: javascript arrays linq.js

我一直在尝试用json.js做几个小时,但对于看似简单的事情来说太过分了。我有这个示例数据:

    var hotels = [
        { id: 101, Name: "Hotel 101", WebFacilities: [8, 9, 10] },
        { id: 102, Name: "Hotel 101", WebFacilities: [8] },
        { id: 103, Name: "Hotel 101", WebFacilities: [8, 10] }
    ];

    var facilities = [
        { id: 8, Name: "Facility 8" },
        { id: 9, Name: "Facility 9" },
        { id: 10, Name: "Facility 10" }
    ];

我想得到这个:

    var selectedFacilities = [
        { id: 8, Name: "Facility 8", Count: 3 },
        { id: 9, Name: "Facility 9", Count: 1 },
        { id: 10, Name: "Facility 10", Count: 2 }
    ];

我该怎么做?

2 个答案:

答案 0 :(得分:2)

所以看起来你正试图计算每个设施的数量。

以下是使用C#编写查询的一种方法:

var hotelFacilities =
    from hotel in hotels
    from id in hotel.WebFacilities
    group id by id;

var query =
    from facility in facilities
    join g in hotelFacilities on facility.id equals g.Key
    select new
    {
        id = facility.id,
        Name = facility.Name,
        Count = g.Count(),
    };

现在,如果您可以使用方法语法对此进行描绘,那么它几乎是对linq.js版本的1:1转换。

请注意,编译器翻译上述内容的方式通常包括之前GroupBy()调用中的SelectMany()调用。无论以这种方式编写,都会使编写linq.js等效查询更容易,也不那么尴尬。

var hotelFacilities = hotels
    .SelectMany(hotel => hotel.WebFacilities)
    .GroupBy(id => id);

var query = facilities
    .Join(
        hotelFacilities,
        facility => facility.id,
        g => g.Key,
        (facility, g) => new
        {
            id = facility.id,
            Name = facility.Name,
            Count = g.Count(),
        }
    );

和等效的linq.js查询。

var hotelFacilities = Enumerable.From(hotels)
    .SelectMany("hotel => hotel.WebFacilities")
    .GroupBy("id => id")
    .ToArray();

var query = Enumerable.From(facilities)
    .Join(
        hotelFacilities,
        "facility => facility.id",
        "g => g.Key()",
        "(facility, g) => { id: facility.id, Name: facility.Name, Count: g.Count() }"
    ).ToArray();

答案 1 :(得分:0)

使用此:

var selectedFacilities = facilities;

for(var i = 0; i < facilities.length; i++) {
    for(var j = 0; j < hotels.length; j++) {
        if(hotels[j]["id"] == facilities[i]["id"]) {
            // Add data
            selectedFacilities[i]["Count"] = hotels[i]["WebFacilities"].length;
        } else {
            selectedFacilities[i]["Count"] = 0;
        }
    }

}