如何展平一组对象? [复制]
Posted
技术标签:
【中文标题】如何展平一组对象? [复制]【英文标题】:How to flatten an array of objects? [duplicate] 【发布时间】:2022-01-21 15:20:19 【问题描述】:我有一些格式不理想的数据,我想将其展平。
数据:
[
team: "Team 1",
name: "John"
,
team: "Team 1",
name: "Stacy"
,
team: "Team 1",
name: "Jason"
,
team: "Team 2",
name: "Tim"
,
team: "Team 2",
name: "Andrew"
,
team: "Team 2",
name: "Steve"
,
team: "Team 3",
name: "Eric"
,
team: "Team 3",
name: "Frank"
,
team: "Team 3",
name: "Cory"
]
想要的结果是:
[
team: "Team 1",
name: ["John", "Stacy", "Jason"],
count: 3
,
team: "Team 2",
name: ["Tim", "Andrew", "Steve"],
count: 3
,
team: "Team 3",
name: ["Eric", "Frank", "Cory"],
count: 3
]
我试过循环遍历它并使用Object.assing
,但这似乎是不正确的方法。关于扁平化这些数据的好方法有什么建议吗?谢谢
【问题讨论】:
您真正想要的是“groupBy”。进行搜索,将找到该操作的许多结果 仅供参考,您所要求的不是扁平化。Array.prototype.flat()
定义了展平数组,而您要求的不是那个。您要求分组。
@Dementic - 您搜索的问题是 OP 实际上并不想要扁平化(他们想要分组),所以 OP 的问题是他们不知道要搜索的正确术语并且没有意识到他们认为它被称为是错误的。这是搜索时偶尔出现的错误。如果您不知道要搜索的正确内容,它可能对您没有帮助。
谢谢@jfriend00 我没有找到合适的结果,因为我想的是扁平化而不是分组。
@Dementic - 如果您查看问题中的实际输入/输出数据,则无需猜测,很明显这不是通用扁平化,这实际上是一个很好的问题(它们包括输入/输出的精确示例)。与 *** 上的许多问题不同,这里不需要猜测。
【参考方案1】:
您可以使用Array.reduce
。
在reducer函数中,检查累加器是否包含具有相同team
属性的项。如果是这样,增加它的count
属性并将当前项目的name
属性推到它的name
属性。
const arr=[team:"Team 1",name:"John",team:"Team 1",name:"Stacy",team:"Team 1",name:"Jason",team:"Team 2",name:"Tim",team:"Team 2",name:"Andrew",team:"Team 2",name:"Steve",team:"Team 3",name:"Eric",team:"Team 3",name:"Frank",team:"Team 3",name:"Cory"];
const res = arr.reduce((a,b) =>
let itm = a.find(e => e.team == b.team);
if(itm)
itm.count++;
itm.name.push(b.name);
else
a.push(team: b.team, name: [b.name], count:1)
return a;
, [])
console.log(res)
更有效的解决方案:
const arr=[team:"Team 1",name:"John",team:"Team 1",name:"Stacy",team:"Team 1",name:"Jason",team:"Team 2",name:"Tim",team:"Team 2",name:"Andrew",team:"Team 2",name:"Steve",team:"Team 3",name:"Eric",team:"Team 3",name:"Frank",team:"Team 3",name:"Cory"];
const obj = arr.reduce((a,b) =>
let itm = a[b.team]
if(itm)
itm.count++;
itm.name.push(b.name);
else
a[b.team] = team: b.team, name: [b.name], count: 0
return a;
, )
const res = Object.keys(obj).map(e => obj[e])
console.log(res)
【讨论】:
以上是关于如何展平一组对象? [复制]的主要内容,如果未能解决你的问题,请参考以下文章