我想以高效的方式在分组之后添加其他包装器
我尝试对每个分组依据进行操作,但是它根据分组值创建了每个数组项目,并带有标题
每个组需要额外的唯一包装,其标题为组标题,并记录为实际的组项目
我在下面显示的预期输出
const records = [{
"id": "po_20",
"name": "po_20",
"searchtype": "purchaseorders"
},
{
"id": "po_10",
"name": "po_10",
"searchtype": "purchaseorders"
},
{
"id": "po_8",
"name": "po_8",
"searchtype": "purchaseorders"
},
{
"id": "po_3",
"name": "po_3",
"searchtype": "purchaseorders"
},
{
"id": "po_17",
"name": "po_17",
"searchtype": "purchaseorders"
},
{
"id": "s1",
"name": "s1",
"searchtype": "sale"
},
{
"id": "s2",
"name": "s2",
"searchtype": "sale"
},
{
"id": "s3",
"name": "s3",
"searchtype": "sale"
}
];
var groups2 = [];
records.forEach(function(item) {
var list = groups2[item.searchtype];
if (list) {
list.push(item);
} else {
groups2[item.searchtype] = [item];
//groups2[title] = [item.group];
}
});
console.log(groups2);
var groups3 = [];
groups2.forEach(function(item) {
console.log("Time");
var jui = [];
jui[title] = item[0].searchtype;
jui[records ] = item;
groups3.push(jui);
});
console.log(groups3);
我希望对象是
const records = [{
title: 'purchaseorders',
records: [{
"id": "po_20",
"name": "po_20",
"searchtype": "purchaseorders"
},
{
"id": "po_10",
"name": "po_10",
"searchtype": "purchaseorders"
},
{
"id": "po_8",
"name": "po_8",
"searchtype": "purchaseorders"
},
{
"id": "po_3",
"name": "po_3",
"searchtype": "purchaseorders"
},
{
"id": "po_17",
"name": "po_17",
"searchtype": "purchaseorders"
}
]
},
{
title: 'sales',
records: [{
"id": "s1",
"name": "s1",
"searchtype": "sales"
},
{
"id": "s2",
"name": "s2",
"searchtype": "sales"
},
{
"id": "s3",
"name": "s3",
"searchtype": "sales"
}
]
}
];
答案 0 :(得分:0)
您可以使用reduce并通过searchtype
键对值进行分组
const records = [{"id": "po_20","name": "po_20","searchtype": "purchaseorders"},{"id": "po_10", "name": "po_10","searchtype": "purchaseorders"},{"id": "po_8","name": "po_8","searchtype": "purchaseorders"},{"id": "po_3","name": "po_3","searchtype": "purchaseorders"},{"id": "po_17","name": "po_17","searchtype": "purchaseorders"},{"id": "s1","name": "s1","searchtype": "sale"},{"id": "s2","name": "s2","searchtype": "sale"},{"id": "s3","name": "s3","searchtype": "sale"}];
let final = records.reduce((op,inp) => {
let title = inp.searchtype
op[title] = op[title] || {title, records:[]}
op[title].records.push(inp)
return op
},{})
console.log(Object.values(final))