javascript - 根据对象的嵌套属性映射新数组
问题描述
我觉得这个问题已经被问了一千次了,但对于我的生活我无法弄清楚,而且对象有些复杂。
我正在建立一个摄影作品集网站,其中画廊包含图像。我收到了来自 Wordpress API 的响应,看起来像这样(简化):
[
{
id: 20,
date: '2020-05-25T20:39:28',
slug: 'test-image',
status: 'inherit',
type: 'attachment',
author: 1,
media_category: [
9
],
acf: {
location: 'North Carolina',
category: {
term_id: 9,
name: 'North Carolina',
slug: 'north-carolina',
term_group: 0,
term_taxonomy_id: 9,
taxonomy: 'media_category',
description: '',
parent: 0,
count: 1,
filter: 'raw'
}
},
... other details
},
... other objects
]
这些只是来自 Wordpress 媒体端点的原始媒体对象。不过,我想要做的是按类别 slug (acf.category.slug) 将它们分组在一起,所以我想我可以有一个外部数组,我可以映射它以供以后使用,然后包含数组(画廊),并且每个数组都包含媒体对象。就像是:
[
[ <-- Gallery 1
{ Image 1 },
{ Image 2 },
],
[ <-- Gallery 2
{ Image 3 },
{ Image 4 },
],
[ <-- Gallery 3
{ Image 5 },
{ Image 6 },
]
]
我希望这是有道理的。
编辑:我想包括我最初的.reduce
功能:
let res = await this.$axios.$get(`${process.env.WP_API_URL}/wp/v2/media`);
const data = res.reduce((images, item) => {
const image = (images[item.acf.category.term_taxonomy_id]);
image.push(item);
images[item.acf.category.slug] = image;
return images;
}, []);
截至目前,我收到一个`TypeError:无法读取未定义的属性'push'。
解决方案
这应该有效:
let res = await this.$axios.$get(`${process.env.WP_API_URL}/wp/v2/media`);
const data = res.reduce((acc, item) => {
const {slug} = item.acf.category;
(acc[slug] || (acc[slug]=[])).push(item)
return acc
}, {});
它生成如下结构:
{
"north-carolina": [
{
id: 20,
date: '2020-05-25T20:39:28',
slug: 'test-image',
status: 'inherit',
type: 'attachment',
author: 1,
media_category: [
9
],
acf: {
location: 'North Carolina',
category: {
term_id: 9,
name: 'North Carolina',
slug: 'north-carolina',
term_group: 0,
term_taxonomy_id: 9,
taxonomy: 'media_category',
description: '',
parent: 0,
count: 1,
filter: 'raw'
}
},
//... other details
},
//... other objects
],
//... objects with different slugs
}
推荐阅读
- python - 如何确定递归中的最后一个堆栈空间
- java - Flutter:我在 Flutter 中遇到了一个问题。我认为问题在于不动态适应的卡
- peewee - 如何在 peewee 中即时将 CharField 转换为 DateTimeField?
- mysql - 将 dockerized mysql 容器部署到边缘设备
- html - CSS下拉菜单不会消失
- reactjs - 如何计算 Firestore 中数组数据中的元素数?
- angular - Angular 7 库 - 如何捆绑依赖项而不将它们添加到主应用程序
- c# - 如何在 Windows 10 上的 UWP 应用和 iOS 设备上的 Xamarin.Forms 应用之间创建 TCP 套接字
- angular - AmCharts 4:网格步骤
- java - Junit 5,Spring 应用程序上下文未在 @DirtiesContext 上关闭