首页 > 解决方案 > 根据对象的嵌套属性映射新数组

问题描述

我觉得这个问题已经被问了一千次了,但对于我的生活我无法弄清楚,而且对象有些复杂。

我正在建立一个摄影作品集网站,其中画廊包含图像。我收到了来自 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'。

标签: javascriptecmascript-6

解决方案


这应该有效:

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
}

在 CodePen 上试用


推荐阅读