javascript - 如何根据某些属性对javascript数组进行分组?
问题描述
我有一个像这样的对象的 JS 数组:
var myArray = [
{ line: 20, text: [31, 80] },
{ line: 10, text: [80, 22] }
]
行在整个 myArray 中是唯一的,每行都有一些文本(不是唯一的)。如何将每个文本与其对应的行匹配?
最终结果应该是这样的:
var myNewArray = [
{ text: 31, line: [20] },
{ text: 80, line: [20, 10] },
{ text: 22, line: [10] }
]
解决方案
一些方法与Map
.
结果你得到一个临时地图,它收集了所有text
,按line
. 要获取对象数组,请将键/值对映射为 eanted 属性。
由于具有嵌套的数据数组,您需要 eiter 对数据进行规范化以获取单个
line
/text
值,然后添加分组 bytext
,const data = [{ line: 20, text: [31, 80] }, { line: 10, text: [80, 22] }], result = Array.from( data .flatMap(({ line, text }) => text.map(text => ({ text, line }))) .reduce((m, { text, line }) => m.set(text, [...(m.get(text) || []), line]), new Map), ([text, line]) => ({ text, line }) ); console.log(result);
或者一步完成,但使用减少外部 (
line
) 和内部数组 (text
数组) 的嵌套方法。const data = [ { line: 20, text: [31, 80] }, { line: 10, text: [80, 22] } ], result = Array.from( data.reduce( (m, { line, text }) => text.reduce( (n, text) => n.set(text, [...(n.get(text) || []), line]), m ), new Map ), ([text, line]) => ({ text, line }) ); console.log(result);
推荐阅读
- java - Spring Data JPA - 方法名称 - @ManyToOne
- python-3.x - Vq 不工作,它在另一个具有相同想法的文件中工作
- azure - 对 Azure Windows Server 2019 虚拟机的 AAD 身份验证
- amazon-web-services - 自定义电子邮件验证页面 AWS Cognito
- bash - bash变量赋值和命令替换中的双引号
- python-3.x - 如何使用变量来确定要使用列表中的哪个索引
- c++ - 如何在到达时将其插入到已满的动态数组中?
- class - 为什么 Dart 中允许使用 new Directory()?
- javascript - 如何在 p5.js 中通过噪声扭曲图像
- javascript - 使用 nodejs 通过 UDP 连接到设备