gpt4 book ai didi

javascript - Javascript 数组中的连接和聚合

转载 作者:行者123 更新时间:2023-12-02 18:58:37 25 4
gpt4 key购买 nike

我已经尝试使用 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 }
];

我该怎么做?

最佳答案

看来您正在尝试计算每个设施有多少个。

这是使用 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 转换。

请注意,编译器转换上述内容的方式通常会在之前的 SelectMany() 调用中包含 GroupBy() 调用。然而,以这种方式编写将使编写 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();

关于javascript - Javascript 数组中的连接和聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15043921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com