首页 > 解决方案 > 使用 es6 为具有相同 id 的项目重新组织数组

问题描述

假设我有一系列产品:

const products = [
 { title: 'test product', storefront: {id: 0, title: 'test storefront 1'} },
 { title: 'test product 2', storefront: {id: 0, title: 'test storefront 1'} },
 { title: 'test product 3', storefront: {id: 1, title: 'test storefront 2'} }
]

我将如何返回一个包含每个店面及其所有产品的对象的新数组?

例如:

  const storefronsts = [
    {
      storefront: {id: 0, title: 'test storefront 1'}, 
      products: [
        { title: 'test product', storefront: {id: 0, title: 'test storefront 1'} }, 
        { title: 'test product 2', storefront: {id: 0, title: 'test storefront 1'} }
      ]
    },
    {
      storefront: {id: 1, title: 'test storefront 2'}, 
      products: [
        { title: 'test product 3', storefront: {id: 1, title: 'test storefront 2'} }
      ]
    }
  ]

标签: javascriptarraystypescriptsortingecmascript-6

解决方案


您可以使用reduce然后检查每个店面id

const rtn = products.reduce((p,c,i,a) => {
    let current = p.find(store => store.storefront.id == c.storefront.id);
    if (!current) { 
        current = { storefront: {id: c.storefront.id, title: c.storefront.title, products: []} }
        p.push(current);
    }

    current.storefront.products.push(c)
    return p;
}, [])

演示:https ://jsfiddle.net/n1pfL8e6/


推荐阅读