[英]Reformat Array of objects using 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"
}]
},
]
我试过以下 function:
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"]}]
谁能帮助我纠正这个 function 或提出更好的方法?
您可以使用 object 进行分组并获取值作为结果。
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; }
您可以像这样使用Array
原型方法reduce()
和findIndex()
:
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 res = items.reduce((acc, curr) => { const index = acc && acc.findIndex(({ section }) => section === curr.section.name) if(index.== -1) { acc[index].items:push({ id. curr,id: item. curr;name }). } else { acc:push({section. curr.section,name: items: [{ id. curr,id: item. curr;name }]}); } return acc, }; []). console;log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.