鹿港巷口少年归

文章 评论 浏览 30

鹿港巷口少年归 2025-02-01 09:56:30

如您所知,变量可以具有多个维度,每个维度可以具有多个值,其中每个值都与名称关联。

有2个重要性索引,第一个是与维度索引相关的索引,我们称其为DimIndex
在您的情况下,只有一个名为module_list的维度,因此,dimIndex必须等于0,

第二个是该维度的值,在您的情况下,module_list具有busman_113和busman_124和busman_124

modules.getDimensions.getDimensions.getDimensions() (0)等于“ busman_113”

模块.getDimensions()[DimIndex] .getIndexName(1)将等于“ Busman_124”

as you know, a variable can have multiple dimensions, and each dimension can have multiple values, where each value is associated to a name.

There are 2 indexes of importance, the first one is the one associated to the index of the dimension, let's call it dimIndex
In your case there's only 1 dimension called Module_List so, dimIndex must be equal to 0

The second one is the value of that dimension, in your case Module_List has values of Busman_113 and Busman_124

Modules.getDimensions()[dimIndex].getIndexName(0) will be equal to "Busman_113"
and
Modules.getDimensions()[dimIndex].getIndexName(1) will be equal to "Busman_124"

获取尺寸阵列的名称

鹿港巷口少年归 2025-01-31 21:00:23

Github不提供此功能。存储库可以包含任意数量的分支和拉请请求。

如果您使用的是GitHub Enterprise Server,则可以使用预先接收的挂钩进行此操作,但是这些挂钩在GitHub.com上不可用。

实际上,您实际上想做一些事情,而不是限制分支机构的数量和拉出请求,这是实现其他目标的一种方式。如果您问一个有关如何实现该目标的新问题,则可能会为可能的问题提供解决方案。

GitHub doesn't offer this functionality. A repository can contain arbitrary numbers of branches and pull requests.

If you're using GitHub Enterprise Server, you can do this with a pre-receive hook, but those are not available on github.com.

It's likely that you actually want to do something other than limit the number of branches and pull requests and that this is a way to achieve some other goal. If you ask a new question about how to achieve that goal, you may get solutions to that problem that are possible.

限制github repo的拉力计数和分支为< n

鹿港巷口少年归 2025-01-31 20:43:43

您可以通过 ID 列和 diff day 列中的 conter 列

df['DAY'] = pd.to_datetime(df['DAY'], dayfirst=True)

from datetime import timedelta

m = timedelta(days=30)

out = df.groupby('ID').apply(lambda group: group[~group['DAY'].diff().abs().le(m)]).reset_index(drop=True)
print(out)

   ID        DAY
0   1 2020-03-22
1   2 2020-05-10
2   2 2020-01-13
3   3 2020-03-30
4   3 2021-02-24

转换为原始日期格式,您可以使用 dt .Strftime

out['DAY'] = out['DAY'].dt.strftime('%d.%m.%Y')
print(out)

   ID         DAY
0   1  22.03.2020
1   2  10.05.2020
2   2  13.01.2020
3   3  30.03.2020
4   3  24.02.2021

You can try group by ID column and diff the DAY column in each group

df['DAY'] = pd.to_datetime(df['DAY'], dayfirst=True)

from datetime import timedelta

m = timedelta(days=30)

out = df.groupby('ID').apply(lambda group: group[~group['DAY'].diff().abs().le(m)]).reset_index(drop=True)
print(out)

   ID        DAY
0   1 2020-03-22
1   2 2020-05-10
2   2 2020-01-13
3   3 2020-03-30
4   3 2021-02-24

To convert to original date format, you can use dt.strftime

out['DAY'] = out['DAY'].dt.strftime('%d.%m.%Y')
print(out)

   ID         DAY
0   1  22.03.2020
1   2  10.05.2020
2   2  13.01.2020
3   3  30.03.2020
4   3  24.02.2021

熊猫:在时间间隔熊猫中出现的滴剂

鹿港巷口少年归 2025-01-31 20:27:07

好吧,迈克(Mike)如“评论”中的评论使用16个字节IV和16、24或32个字节的密钥大小,因此不可能加密字符串或任何内容,除非您为您做了一些技巧,否则使用短IV和键示例用零的值扩展长度,直到它变为16个字节。.

您可以非常简单地将您的密码转换为iv并添加零,直到在您的情况下变为16个“ asdfghjkl ”将是在十六进制中“ 61 73 64 66 67 68 68 6B 6B 6C ”,因此您需要添加 0000000000000000 这样它将在没有任何错误的情况下工作。 。

Well Mike as in the comments AES uses a 16 bytes IV and 16, 24 or 32 bytes for the key size , so it is not possible to encrypt the Strings or whatever it was, with a short IV and Key unless u did some tricks for example extend the length with the value of Zeros until it becomes 16 Byte..

You can very simply convert ur password and IV to hex and add zeros until it becomes 16 in ur case the "asdfghjkl" will be in hex "61 73 64 66 67 68 6a 6b 6c " so u will need to add 00000000000000 this way it will work without any errors.. but it is not secure.. in python u can use unhexlify() to convert the hex key and iv to bytes.

如何用特定键和IV长度加密AES / CBC 128

鹿港巷口少年归 2025-01-31 12:35:28

您可以使用中单击拖拉来完成您想做的事情,尽管它非常糟糕。

You can use middle-click-drag to do what you want, although it's pretty awful.

我可以像notepadd++?

鹿港巷口少年归 2025-01-31 11:12:22

我发现了seluce:

public function forceLogout() : void
{
    $logoutEvent = new LogoutEvent($this->requestStack->getCurrentRequest(), $this->tokenStorage->getToken());
    $this->eventDispatcher->dispatch($logoutEvent);
    $this->tokenStorage->setToken(null);
    $response = new Response();
    $response->headers->clearCookie('REMEMBERME');
    $response->send();
}

I found soluce :

public function forceLogout() : void
{
    $logoutEvent = new LogoutEvent($this->requestStack->getCurrentRequest(), $this->tokenStorage->getToken());
    $this->eventDispatcher->dispatch($logoutEvent);
    $this->tokenStorage->setToken(null);
    $response = new Response();
    $response->headers->clearCookie('REMEMBERME');
    $response->send();
}

Symfony 6.0-控制器中的强制注销用户

鹿港巷口少年归 2025-01-31 05:06:13

PL/PGSQL支持函数内部的变量,因此,如果需要,您可以使其成为一个函数,然后查询函数结果。说类似的话:

CREATE FUNCTION get_user_interaction_counts
(
   date_start date,
   date_end date
)
RETURNS TABLE(user_id int, like_count int, comment_count int) as $
SELECT u.id, likes.likes, comments.comments
FROM "user" u
JOIN (SELECT user_id, count(*) as likes
    FROM likes l
    WHERE l.created_on > date_start AND l.created_on <= date_end
    GROUP BY l.user_id
) as likes ON u.id = likes.user_id
JOIN (
    SELECT user_id, count(*) as comments
    FROM comment c
    WHERE c.created_on > date_start AND c.created_on <= date_end
    GROUP BY c.user_id
) as comments ON u.id = comments.user_id

$ LANGUAGE SQL;

您会查询它:

select * from get_user_interaction_counts('2021-10-01', '2021-10-30')

当然,这可能不是您所追求的。如果“只是查询”时想要变量,它将取决于您正在使用的客户端。如果您使用的是PSQL,则它确实支持变量。其他客户可能会或可能不会支持他们,取决于他们。

您还可以做的是像这样稍微刷新查询,然后使用参数CTE,然后使用它加入选定的参数:

WITH parameters AS (
  SELECT '2021-10-01'::date as date_start
       , '2021-10-30'::date as date_end
)
SELECT u.id, likes.likes, comments.comments
FROM "user" u
JOIN (SELECT user_id, count(*) as likes
    FROM likes l
    JOIN parameters par
      ON l.created_on > par.date_start AND l.created_on <= par.date_end
    GROUP BY l.user_id
) as likes ON u.id = likes.user_id
JOIN (
    SELECT user_id, count(*) as comments
    FROM comment c
    JOIN parameters par
      ON c.created_on > par.date_start AND c.created_on <= par.date_end
    GROUP BY c.user_id
) as comments ON u.id = comments.user_id

这是一个带有两个

ps的DBFIDDLE演示。您的查询使用内部加入,因此仅包括喜欢和评论的用户。如果用户没有发表评论或不喜欢任何内容,则将被排除在外,因为不会从加入查询中返回任何记录。

PL/pgSQL supports variables inside functions, so you could make this a function if you wanted and then query the function results. Say something like:

CREATE FUNCTION get_user_interaction_counts
(
   date_start date,
   date_end date
)
RETURNS TABLE(user_id int, like_count int, comment_count int) as $
SELECT u.id, likes.likes, comments.comments
FROM "user" u
JOIN (SELECT user_id, count(*) as likes
    FROM likes l
    WHERE l.created_on > date_start AND l.created_on <= date_end
    GROUP BY l.user_id
) as likes ON u.id = likes.user_id
JOIN (
    SELECT user_id, count(*) as comments
    FROM comment c
    WHERE c.created_on > date_start AND c.created_on <= date_end
    GROUP BY c.user_id
) as comments ON u.id = comments.user_id

$ LANGUAGE SQL;

You'd then query it:

select * from get_user_interaction_counts('2021-10-01', '2021-10-30')

Of course that's probably not what you're after. If you want variables when "just querying", it'll depend on the client you're using. If you're using psql, it does support variables. Other clients may or may not support them, depends.

What you can also do is to rework the query a little bit, like so, with a parameters CTE at the beginning and then use it to join the selected params:

WITH parameters AS (
  SELECT '2021-10-01'::date as date_start
       , '2021-10-30'::date as date_end
)
SELECT u.id, likes.likes, comments.comments
FROM "user" u
JOIN (SELECT user_id, count(*) as likes
    FROM likes l
    JOIN parameters par
      ON l.created_on > par.date_start AND l.created_on <= par.date_end
    GROUP BY l.user_id
) as likes ON u.id = likes.user_id
JOIN (
    SELECT user_id, count(*) as comments
    FROM comment c
    JOIN parameters par
      ON c.created_on > par.date_start AND c.created_on <= par.date_end
    GROUP BY c.user_id
) as comments ON u.id = comments.user_id

Here's a dbfiddle demo with both

PS. Your queries use inner join so will only include users who both liked and commented. If a user didn't comment, or didn't like anything, they will be excluded because no records will be returned from the joined query.

当从多个内部查询中汇总数据时,如何避免冗长和简化?

鹿港巷口少年归 2025-01-31 04:00:24

问题1:

有人可以解释私人和共享扩展属性之间的区别吗?

官方文件显示如下。

  • ExtendedProperties.private :属于此日历上事件副本的属性。
  • ExtendedProperties.shared :事件副本之间在其他与会者日历上共享的属性。

例如,当创建一个新事件,并使用 extendedProperties.private and extendedProperties.shared 通过包括与会者,您可以看到两个值。但是,与会者只能看到 ExtendedProperties.shared 的值。

这种解释有用吗?

问题2的答案:

我想在Google脚本= .gs文件中添加 /插入带有扩展属性的新事件。< / p>

当我看到 createEvent方法的正式文档(标题,开始时间,末日,选项)时,似乎 options 没有 ExtendedProperties 。 ref 我认为这是您问题的原因。如果要创建一个新事件,包括 extendedProperties.private ExtendedProperties.shared 的值,如何使用高级Google Services的日历API?

示例脚本如下。

const calendarId = "###"; // Please set your calendar ID.

// Create a new event including extendedProperties.
const params = {
  start: { dateTime: "2022-04-27T00:00:00Z" },
  end: { dateTime: "2022-04-27T01:00:00Z" },
  extendedProperties: {
    private: { key1: "value1" },
    shared: { key2: "value2" }
  },
  summary: "sample",
  attendees: [{ email: "###" }] // Please set the email of attendee, if you want to include.
};
const res1 = Calendar.Events.insert(params, calendarId);

// Check the value of extendedProperties
const res2 = Calendar.Events.get(calendarId, res1.id);
console.log(res2.extendedProperties)
  • 当此脚本由日历的所有者运行时,您可以看到 extendedProperties.private extendedProperties.shared 的两个值。
  • 当您获得与会者的事件时,您只能看到 ExtendedProperties.shared 的值。

参考:

Answer for question 1:

Could someone please explain the difference between private and shared extended properties?

The official document says as follows.

  • extendedProperties.private: Properties that are private to the copy of the event that appears on this calendar.
  • extendedProperties.shared: Properties that are shared between copies of the event on other attendees' calendars.

For example, when a new event is created with the values of extendedProperties.private and extendedProperties.shared by including the attendees, you can see both values. But, the attendees can see only the value of extendedProperties.shared.

Is this explanation useful?

Answer for question 2:

I want to add / insert new event with extened properties in Google Script = .gs file.

When I saw the official document of the method of createEvent(title, startTime, endTime, options), it seems that options has no property of extendedProperties. Ref I thought that this is the reason for your issue. If you want to create a new event including the values of extendedProperties.private and extendedProperties.shared, how about using Calendar API of Advanced Google services?

The sample script is as follows.

const calendarId = "###"; // Please set your calendar ID.

// Create a new event including extendedProperties.
const params = {
  start: { dateTime: "2022-04-27T00:00:00Z" },
  end: { dateTime: "2022-04-27T01:00:00Z" },
  extendedProperties: {
    private: { key1: "value1" },
    shared: { key2: "value2" }
  },
  summary: "sample",
  attendees: [{ email: "###" }] // Please set the email of attendee, if you want to include.
};
const res1 = Calendar.Events.insert(params, calendarId);

// Check the value of extendedProperties
const res2 = Calendar.Events.get(calendarId, res1.id);
console.log(res2.extendedProperties)
  • When this script is run by the owner of the calendar, you can see both values of extendedProperties.private and extendedProperties.shared.
  • When you get this event by the attendee, you can see only the value of extendedProperties.shared.

References:

如何在GS中使用扩展属性插入Google事件?

鹿港巷口少年归 2025-01-30 17:34:07

问题在于,您使用相同的变量 y 作为原始列表。

在原始代码块中,您不重新签名 y ,直到 list()在列表上迭代。因此,在 lambda 中, y 是指原始列表,您可以使用 y [i] 访问这些列表元素。

但是在您将 map()结果分配给变量的版本中地图对象,而不是原始列表。您会得到该错误,因为 MAP 对象无法索引,而只迭代。

The problem is that you're using the same variable y for the map as the original list.

In the original code block, you don't reassign y until after list() has iterated over the list. So inside the lambda, y refers to the original list, and you can use y[i] to access those list elements.

But in the version where you assign the result of map() to the variable, y[i] in the lambda is trying to access the map object, not the original list. You get that error because the map object cannot be indexed, only iterated.

在python中,为什么x = list(map(x))还可以,但是x = map(x); x =列表(x)导致错误?

鹿港巷口少年归 2025-01-30 09:29:00

由于您有 Xmatch(),您不能只切换到 filter()吗?

例如:

=FILTER(ROW(B2:B12),B1:B11=A2)

或者,只需避免使用返回的位置,然后直接过滤您想要的任何东西。这里没有特定的字符限制可以阻止您,并且不使用 mid()的奇怪构造,您确实确实具有完全匹配的。

Since you have XMATCH(), can't you just switch to FILTER()?

For example:

=FILTER(ROW(B2:B12),B1:B11=A2)

Or, just avoid using the returned position and directly filter whatever you like to. No specific character limit here to hold you back and isntead of a strange construction with MID() you do actually have exact matching.

在匹配公式中添加中间功能

鹿港巷口少年归 2025-01-30 08:22:47

可变插值根本不起作用。

但是您可以使用CSS变量:

@mixin defineVars($id) {
  --#{$id}-background-color: tomato;
  --#{$id}-background-image: null;
  --#{$id}-background-size: null;
  --#{$id}-background-position-x: null;
  --#{$id}-background-position-y: null;
  --#{$id}-background-repeat: null;
  --#{$id}-color: null;
  --#{$id}-border-radius: null;
  --#{$id}-border-width: null;
  --#{$id}-border-color: null;
  --#{$id}-padding: null;
  --#{$id}-margin: null;
}

:root {
  @include defineVars('some-id');
}

body {
  background-color: var(--some-id-background-color);
}

SCSS块的输出:

:root {
    --some-id-background-color: tomato;
    --some-id-background-image: null;
    --some-id-background-size: null;
    --some-id-background-position-x: null;
    --some-id-background-position-y: null;
    --some-id-background-repeat: null;
    --some-id-color: null;
    --some-id-border-radius: null;
    --some-id-border-width: null;
    --some-id-border-color: null;
    --some-id-padding: null;
    --some-id-margin: null;
}

body {
    background-color: var(--some-id-background-color);
}

Variable interpolation does not work at all.

But you can use CSS variables:

@mixin defineVars($id) {
  --#{$id}-background-color: tomato;
  --#{$id}-background-image: null;
  --#{$id}-background-size: null;
  --#{$id}-background-position-x: null;
  --#{$id}-background-position-y: null;
  --#{$id}-background-repeat: null;
  --#{$id}-color: null;
  --#{$id}-border-radius: null;
  --#{$id}-border-width: null;
  --#{$id}-border-color: null;
  --#{$id}-padding: null;
  --#{$id}-margin: null;
}

:root {
  @include defineVars('some-id');
}

body {
  background-color: var(--some-id-background-color);
}

Output of SCSS block:

:root {
    --some-id-background-color: tomato;
    --some-id-background-image: null;
    --some-id-background-size: null;
    --some-id-background-position-x: null;
    --some-id-background-position-y: null;
    --some-id-background-repeat: null;
    --some-id-color: null;
    --some-id-border-radius: null;
    --some-id-border-width: null;
    --some-id-border-color: null;
    --some-id-padding: null;
    --some-id-margin: null;
}

body {
    background-color: var(--some-id-background-color);
}

您可以在SCSS中动态定义变量名称吗?

鹿港巷口少年归 2025-01-30 05:39:36

如果语句使用使用来设置是否提供该字段的条件。

exports.updateUser = (req, res, next) => {
  try {
    let image = null;
    if (req.?file.?filename) {
      image = `${req.protocol}://${req.get('host')}/images/${req.file.filename}`;
    }
    if (res.locals.userId === parseInt(req.params.id)) {
      const user = [
        req.body.user_lastName,
        req.body.user_firstName,
        image,
        req.params.id
      ]
      const sql = "UPDATE users SET user_lastName=?, user_firstName=?,user_avatar=? WHERE user_id=?";
      db.query(sql, user, function(error, results) {
        if (!error) {
          res.status(200).json({
            message: 'modification profil executé'
          });
        } else {
          console.log(error)
          res.status(401).json({
            error: 'Erreur utilisateur table users'
          });
        }
      });

    } else {
      res.status(401).json({
        error: 'erreur d\'authentification, vous n\'avez pas les droits pour modifier ce profil'
      })
    }
  } catch (error) {
    res.status(500).json({
      error
    });
    console.log(error)
  }
}

Use an if statement to set a variable conditional on whether the field was provided.

exports.updateUser = (req, res, next) => {
  try {
    let image = null;
    if (req.?file.?filename) {
      image = `${req.protocol}://${req.get('host')}/images/${req.file.filename}`;
    }
    if (res.locals.userId === parseInt(req.params.id)) {
      const user = [
        req.body.user_lastName,
        req.body.user_firstName,
        image,
        req.params.id
      ]
      const sql = "UPDATE users SET user_lastName=?, user_firstName=?,user_avatar=? WHERE user_id=?";
      db.query(sql, user, function(error, results) {
        if (!error) {
          res.status(200).json({
            message: 'modification profil executé'
          });
        } else {
          console.log(error)
          res.status(401).json({
            error: 'Erreur utilisateur table users'
          });
        }
      });

    } else {
      res.status(401).json({
        error: 'erreur d\'authentification, vous n\'avez pas les droits pour modifier ce profil'
      })
    }
  } catch (error) {
    res.status(500).json({
      error
    });
    console.log(error)
  }
}

条件有mysql请求

鹿港巷口少年归 2025-01-29 18:49:10

您在正确的轨道上, grepl 是您的朋友。这样您就可以使用其中的国家,糊剂它们一起倒在 | 上。

然后,使用子集

EU_p <- paste(EU, collapse='|')

subset(df, grepl(EU_p, a))
#                     a b
# 2         Croatia USA 2
# 4 Switzerland Hungary 4
# 5 Lithuania Indonesia 5

或使用括号所示,

df[grepl(EU_p, df$a), ]
#                     a b
# 2         Croatia USA 2
# 4 Switzerland Hungary 4
# 5 Lithuania Indonesia 5

结果是 df 至少包含 eu 向量的任何一行位置。


数据:

df <- structure(list(a = c("Albania Canada", "Croatia USA", "Mexico Egypt", 
"Switzerland Hungary", "Lithuania Indonesia"), b = c(1, 2, 3, 
4, 5)), class = "data.frame", row.names = c(NA, -5L))

You were on the right track, grepl is your friend. So that you can use the countries with it, paste them together while collapsing on an or |.

Then, using subset

EU_p <- paste(EU, collapse='|')

subset(df, grepl(EU_p, a))
#                     a b
# 2         Croatia USA 2
# 4 Switzerland Hungary 4
# 5 Lithuania Indonesia 5

or as you indicated using brackets

df[grepl(EU_p, df$a), ]
#                     a b
# 2         Croatia USA 2
# 4 Switzerland Hungary 4
# 5 Lithuania Indonesia 5

The result is any row of df containing at least one country of the EU vector, since the pattern as is doesn't distinguish the position.


Data:

df <- structure(list(a = c("Albania Canada", "Croatia USA", "Mexico Egypt", 
"Switzerland Hungary", "Lithuania Indonesia"), b = c(1, 2, 3, 
4, 5)), class = "data.frame", row.names = c(NA, -5L))

如何使用包含另一个变量的部分字符串的列表来子集数据框

鹿港巷口少年归 2025-01-29 17:21:44

原因可能是您使用的是path_provider函数“ getApplicationDocumentsDirectory()”来存储文件。通过用“ getExternalStoreDirectory()”替换上述函数,您可以将文件存储在外部目录中以显示在图库中。如果那不起作用,您也可以使用此插件:
https://pub.dev/packages/gallery_saver

The reason might be that you are using the path_provider function "getApplicationDocumentsDirectory()" to store the files. By replacing above Function with "getExternalStorageDirectory()" you would able to store the file in the external directory to appear in gallery. If that doesn’t work you can also use this plugin:
https://pub.dev/packages/gallery_saver

扑来:我需要干净的方法来使用youtube_explode_dart软件包来保存视频

鹿港巷口少年归 2025-01-29 10:15:25

使用 type 作为密钥,将数组减少到地图。使用 array.from()将地图的值迭代器转换为数组:

const arr = [{"id":1,"name":"a","type":"foo"},{"id":2,"name":"b","type":"bar"},{"id":3,"name":"c","type":"fizz"},{"id":4,"name":"d","type":"foo"}]

const result = Array.from(arr.reduce((acc, o) => {
  const type = o.type
  if(!acc.has(type)) acc.set(type, { type, groups: [] })
  
  acc.get(type).groups.push(o)
  
  return acc
}, new Map()).values())

console.log(result)

要使TS推断分组数组的类型,请从原始数组中推断项目的类型,然后使用它设置地图的类型(TS playground):

const arr = [{"id":1,"name":"a","type":"foo"},{"id":2,"name":"b","type":"bar"},{"id":3,"name":"c","type":"fizz"},{"id":4,"name":"d","type":"foo"}]

type Item = (typeof arr)[0]

const result = Array.from(arr.reduce((acc, o) => {
  const type = o.type
  if(!acc.has(type)) acc.set(type, { type, groups: [] })
  
  acc.get(type)!.groups.push(o)
  
  return acc
}, new Map<string, { type: Item['type'], groups: Item[] }>()).values())

console.log(result)

Another option is to reduce the array to a map of groups [type, object] ,然后使用 array.from()将映射的条目转换为所需的形式(TS playground):

const arr = [{"id":1,"name":"a","type":"foo"},{"id":2,"name":"b","type":"bar"},{"id":3,"name":"c","type":"fizz"},{"id":4,"name":"d","type":"foo"}]

const result = Array.from(
  arr.reduce((acc, o) => {
    const type = o.type
    if(!acc.has(type)) acc.set(type, [])

    acc.get(type).push(o)

    return acc
  }, new Map()),
  ([type, groups]) => ({ type, groups })
)

console.log(result)

Reduce the array to a Map, using the type as the key. Use Array.from() to convert the Map's values iterator to an array:

const arr = [{"id":1,"name":"a","type":"foo"},{"id":2,"name":"b","type":"bar"},{"id":3,"name":"c","type":"fizz"},{"id":4,"name":"d","type":"foo"}]

const result = Array.from(arr.reduce((acc, o) => {
  const type = o.type
  if(!acc.has(type)) acc.set(type, { type, groups: [] })
  
  acc.get(type).groups.push(o)
  
  return acc
}, new Map()).values())

console.log(result)

To make TS infer the type of the grouped array, infer the type of an item from the original array, and use it to set the type of the Map (TS playground):

const arr = [{"id":1,"name":"a","type":"foo"},{"id":2,"name":"b","type":"bar"},{"id":3,"name":"c","type":"fizz"},{"id":4,"name":"d","type":"foo"}]

type Item = (typeof arr)[0]

const result = Array.from(arr.reduce((acc, o) => {
  const type = o.type
  if(!acc.has(type)) acc.set(type, { type, groups: [] })
  
  acc.get(type)!.groups.push(o)
  
  return acc
}, new Map<string, { type: Item['type'], groups: Item[] }>()).values())

console.log(result)

Another option is to reduce the array to a map of groups [type, object], and then use Array.from() to convert the Map's entries to the required form (TS playground):

const arr = [{"id":1,"name":"a","type":"foo"},{"id":2,"name":"b","type":"bar"},{"id":3,"name":"c","type":"fizz"},{"id":4,"name":"d","type":"foo"}]

const result = Array.from(
  arr.reduce((acc, o) => {
    const type = o.type
    if(!acc.has(type)) acc.set(type, [])

    acc.get(type).push(o)

    return acc
  }, new Map()),
  ([type, groups]) => ({ type, groups })
)

console.log(result)

从现有对象从现有对象添加现有对象到新数组,创建一个新的对象数组

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文