Мне нужно сгруппировать массив ниже с похожим типом и отделить каждое описание запятой.
Введите
let obj=[
{
"type": "Bedroom",
"int_input": 1,
"enum_input": 0,
"enum_select": "Yes",
"description": "Test"
},
{
"type": "Bedroom",
"int_input": 1,
"enum_input": 0,
"enum_select": "Yes",
"description": "Test1"
},
{
"type": "Bedroom",
"int_input": 1,
"enum_input": 0,
"enum_select": "Yes",
"description": "Test"
},
{
"type": "Bathroom",
"int_input": 1,
"enum_input": 0,
"enum_select": "Yes",
"description": "Test"
},
{
"type": "Bathroom",
"int_input": 1,
"enum_input": 0,
"enum_select": "Yes",
"description": "Test"
},
{
"type": "Bathroom",
"int_input": 1,
"enum_input": 0,
"enum_select": "Yes",
"description": "Test"
}
]
выход
let finalobj=[
{
"type": "Bedroom",
"description": "Test,Test1,Test"
},
{
"type": "Bathroom",
"description": "Test,Test,Test"
}
]
Моя попытка (я довольно близка, но в первом сете получаю неопределенность)
let obj=[
{
"type": "Bedroom",
"int_input": 1,
"enum_input": 0,
"enum_select": "Yes",
"description": "Test"
},
{
"type": "Bedroom",
"int_input": 1,
"enum_input": 0,
"enum_select": "Yes",
"description": "Test1"
},
{
"type": "Bedroom",
"int_input": 1,
"enum_input": 0,
"enum_select": "Yes",
"description": "Test"
},
{
"type": "Bathroom",
"int_input": 1,
"enum_input": 0,
"enum_select": "Yes",
"description": "Test"
},
{
"type": "Bathroom",
"int_input": 1,
"enum_input": 0,
"enum_select": "Yes",
"description": "Test"
},
{
"type": "Bathroom",
"int_input": 1,
"enum_input": 0,
"enum_select": "Yes",
"description": "Test"
}
]
//first take the type
let type_only=obj.map(o=>o.type);
type_only=Array.from(new Set(type_only));
let sum_obj={};
let arr=[];
//iterate types
{type_only.map((val,index) =>{
sumobj = obj.reduce((c, v) => v.type === val ? {'description': (c.description + ','+ v.description),'type':v.type} : c, 0)
arr.push(sumobj);
}
)}
console.log(arr);
console.log(type_only);