给定一个具有一些常见属性的对象数组,例如foosWithBar
,如何在barsWithFoos
不使用 lodash 之类的库的情况下创建另一个按这些常见属性分组的对象数组?我找到了创建按 key 分组的对象的示例reduce()
,但这并不是我想要的。
const foosWithBar = [
{
id: 'Foo A',
bar: {
id: 'Bar 1',
},
},
{
id: 'Foo B',
bar: {
id: 'Bar 1',
},
},
{
id: 'Foo C',
bar: {
id: 'Bar 2',
},
},
{
id: 'Foo D',
bar: {
id: 'Bar 2',
},
},
]
const barsWithFoos = [
{
id: 'Bar 1',
foos: [
{
id: 'Foo A',
},
{
id: 'Foo B',
},
],
},
{
id: 'Bar 2',
foos: [
{
id: 'Foo C',
},
{
id: 'Foo D',
},
],
},
]