javascript - 使用 array.map 重新格式化对象数组
问题描述
我收到带有以下数组的 API 调用的结果,我正在尝试从以下位置重新格式化此数组:
const items = [
{
id: 1,
name: "Item 1",
section: { name: "Section A" }
},
{
id: 2,
name: "Item 2",
section: { name: "Section A" }
},
{
id: 3,
name: "Item 3",
section: { name: "Section A" }
},
{
id: 4,
name: "Item 4",
section: { name: "Section B" }
},
{
id: 5,
name: "Item 5",
section: { name: "Section B" }
},
{
id: 6,
name: "Item 6",
section: { name: "Section C" }
},
{
id: 7,
name: "Item 7",
section: { name: "Section C" }
}
];
排列这个:
const items = [
{
section: "Section A",
items: [
{
id: 1,
item: "Item 1"
},
{
id: 2,
item: "Item 2"
},
{
id: 3,
item: "Item 3"
}]
},
{
section: "Section B",
items: [
{
id: 4,
item: "Item 4"
},
{
id: 5,
item: "Item 5"
}]
},
{
section: "Section C",
items: [
{
id: 6,
item: "Item 6"
},
{
id: 7,
item: "Item 7"
}]
},
]
我尝试了以下功能:
const result = Array.from(new Set(items.map(s => s.section.name)))
.map(section => {
return {
section: section,
items: Array.from(new Set(items.map(function (item) {
if (item.section.name === section) {
return item.name
}
}
)))
}
})
这给了我以下结果,这很接近,但我不确定为什么我得到未定义的值?
//[{section: "Section A", items: ["Item 1", "Item 2", "Item 3", undefined]},{section: "Section B", items:[undefined, "Item 4", "Item 5"]},{section: "Section C", items: [undefined, "Item 6", "Item 7"]}]
任何人都可以帮助我更正此功能或提出更好的方法吗?
解决方案
您可以使用一个对象进行分组并获取值作为结果。
const
items = [{ id: 1, name: "Item 1", section: { name: "Section A" } }, { id: 2, name: "Item 2", section: { name: "Section A" } }, { id: 3, name: "Item 3", section: { name: "Section A" } }, { id: 4, name: "Item 4", section: { name: "Section B" } }, { id: 5, name: "Item 5", section: { name: "Section B" } }, { id: 6, name: "Item 6", section: { name: "Section C" } }, { id: 7, name: "Item 7", section: { name: "Section C" } }],
result = Object.values(items.reduce((r, { section: { name: section }, ...item }) => {
if (!r[section]) r[section] = { section, items: [] };
r[section].items.push(item);
return r;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- php - 通过 PHP 创建一个 WC_Product_Subscription_Variation 并设置所需的帖子元(周期和周期间隔)
- sql - sql初学者是否有命令,所以我不能将空值传递到表中?
- python - python 3.7.3 - concurent.futures 等待麻烦
- javascript - 收到4xx状态码响应时如何阻止axios抛出的错误?
- python - 每组最低条件
- java - 使用 java 或 python 在 excel 数值数据上实现掩蔽算法(例如:噪声添加)
- python - varibale "count" won't be incremented even though if statement ,to increment it, matches the condition
- excel - VBA复制范围到所有工作表都优于复制的一个
- c++ - C ++从深堆栈向调用者返回值而没有“抛出”
- spring-boot - org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“customerController”的bean时出错:不满足的依赖项