[英]Javascript - Filter and/or Group Array of Objects by property
嗨,我有這個對象數組
{
"events": [
{
"id": 0,
"description": "Monthly play with friends",
"categoryId": 0
},
{
"id": 1,
"description": "Buy Goods",
"categoryId": 2
},
{
"id": 2,
"description": "Yoga",
"categoryId": 1
},
{
"id": 3,
"description": "Lunch",
"categoryId": 0
},
{
"id": 4,
"description": "Feed wild & free Bearded Dragons",
"categoryId": 3
},
{
"id": 5,
"description": "Come to help our little friends",
"categoryId": 3
},
{
"id": 6,
"description": "Come and share your expertise",
"categoryId": 3
},
{
"id": 7,
"description": "Dinner with Brother",
"categoryId": 2
}
]
}
我需要顯示按 CategoryId 分組的項目,將 CategoryID 顯示為組的標題,然后在里面列出該類別的項目。
CategoryId 0 每月和朋友一起玩午餐
CategoryId 1 瑜伽
CategoryId 2 買貨和兄弟吃飯
等等....
嘗試使用Array.prototype.reduce()
function:
let ans = events.reduce((cum, x) => {
if (cum['category ' + x.categoryId] == null) {
cum['category ' + x.categoryId] = [x.description];
return cum;
} else {
cum['category ' + x.categoryId].push(x.description);
return cum;
}
}, {});
const groupedBy = (array) => { const grouped = [] let types = [...new Set(array.map(({ type }) => type))] types.forEach((type) => { grouped.push({ [type]: array.filter(a => a.type === type) }) }) return grouped } groupedBy([{ name: 'h', type: 'user' }, { name: 'r', type: 'user' }, { name: 'v', type: 'user' }, { name: 'p', type: 'admin' }, { name: 'k', type: 'admin' }])
一個 ez for 循環就足夠了:
const data = { events: ... }
var obj = {};
for (let event of data.events) {
// if empty, creates a array
obj[event.categoryId] = obj[event.categoryId] || [];
// add data in that array
obj[event.categoryId].push(event);
}
現在每個 categoryId 都有一個表格,可以隨意顯示
for (let categoryId in obj) {
console.log(categoryId, obj[categoryId]);
// or
// console.log(categoryId, obj[categoryId].map(x => x.description).join(','));
}
您需要創建一個具有與類別相同數量的索引的二維數組。 在每個索引中,將包含與該類別匹配的所有描述的數組
然后,您需要為數組中的每個 object 運行一個 for 循環,將它們的“描述”值存儲在相關索引中。
然后,您可以打印索引(將匹配 category )以及包含的所有描述
var events= [
{
"id": 0,
"description": "Monthly play with friends",
"categoryId": 0
},
{
"id": 1,
"description": "Buy Goods",
"categoryId": 2
},
{
"id": 2,
"description": "Yoga",
"categoryId": 1
},
{
"id": 3,
"description": "Lunch",
"categoryId": 0
},
{
"id": 4,
"description": "Feed wild & free Bearded Dragons",
"categoryId": 3
},
{
"id": 5,
"description": "Come to help our little friends",
"categoryId": 3
},
{
"id": 6,
"description": "Come and share your expertise",
"categoryId": 3
},
{
"id": 7,
"description": "Dinner with Brother",
"categoryId": 2
}
];
var eventGroup = [];
for(var i in events){
if(parseInt(events[i].categoryId) >= eventGroup.length){
while(eventGroup.length <= parseInt(events[i].categoryId)){
eventGroup.push([]);
}
}
console.log(eventGroup);
eventGroup[parseInt(events[i].categoryId)].push(events[i].description);
}
for(var f= 0 ; f< eventGroup.length; f++){
console.log(f + " " + eventGroup[f]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.