[英]JavaScript: Rebuild Array of Objects using Reduce
I have an array of objects that I'm trying to rebuild without any success:我有一组对象,我试图重建但没有成功:
const data = [
{
ID: 1,
TemplateName: 'Template 1',
TemplateCategory: 'Category A',
},
{
ID: 2,
TemplateName: 'Template 2',
TemplateCategory: 'Category A',
},
{
ID: 3,
TemplateName: 'Template 3',
TemplateCategory: 'Category B',
},
]
I have the below code which produces the following undesired result:我有以下代码,它会产生以下不良结果:
result = [...data
.reduce((acc, {TemplateCategory, TemplateName, ID}) => {
const group = acc.get(TemplateCategory)
group ? group.options.push(ID, TemplateName) : acc.set(TemplateCategory, {TemplateCategory, "options":[ID, TemplateName]})
return acc
}, new Map)
.values()
]
console.log(result) // undesired result:
[
{
TemplateCategory: 'Category A',
options: [1, 'Template 1', 2, 'Template 2']
},
{
TemplateCategory: 'Category B',
options: [3, 'Template 3']
}
]
I am stuck on trying to convert options
to an Array of Objects with value
and label
as properties.我坚持尝试将
options
转换为具有value
和label
作为属性的对象数组。 Also im struggling trying to reword TemplateCategory
property to label
.我也在努力尝试将
TemplateCategory
属性改写为label
。
My desired result is:我想要的结果是:
[
{
label: 'Category A',
options: [
{
value: 1,
label: 'Template 1'
},
{
value: 2,
label: 'Template 2'
}
]
},
{
label: 'Category B',
options: [
{
value: 3,
label: 'Template 3'
}
]
}
]
TIA TIA
Like this像这样
const data = [ { ID: 1, TemplateName: 'Template 1', TemplateCategory: 'Category A', }, { ID: 2, TemplateName: 'Template 2', TemplateCategory: 'Category A', }, { ID: 3, TemplateName: 'Template 3', TemplateCategory: 'Category B', }, ] const result = [...data.reduce((acc, {TemplateCategory, TemplateName, ID}) => { const group = acc.get(TemplateCategory) group? group.options.push({value: ID, label: TemplateName}): acc.set(TemplateCategory, {label: TemplateCategory, "options":[{value: ID, label: TemplateName}]}) return acc }, new Map).values() ] console.log(result) // undesired result:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.