javascript - 使用 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'} }
]
}
]
解决方案
您可以使用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;
}, [])
推荐阅读
- android - 如何根据基本适配器列表视图中的不同字符串更改颜色
- python - 字符串列表最大值python
- jquery - 无法在 jquery 函数中设置全局变量
- c# - 在 LINQ 连接中包含多个 ON
- asp.net - 使用来自 asp.net 的 Windows 凭据登录到 sql server
- mysql - 数据库模型:我应该将学生的最终成绩存储在数据库中吗
- algorithm - 为什么基数排序是 O(nd) 而归并排序不是 O(d*nlogn)?
- apache - 第三次 REST 连接失败
- arrays - 在数组中找到可重复的字符串位置
- kiwi-tcms - 安装kiwi tcms时出现django.db.migrations.exceptions.InconsistentMigrationHistory错误