我正在嘗試“展平”具有多個重復值的陣列。該陣列是從我嘗試在其上運行 API 請求的 CSV 創建的。CSV 的格式如下:
Posts | Comments |
post1 comment1
post1 comment2
post1 comment3
post2 comment1
post2 comment2
post2 comment3
我正在使用回傳的 Papaparse:
[{Post: 'post1', Comment: 'comment1'}, {Post: 'post1', Comment: 'comment2'}, ...]
所以我想我會嘗試將它們展平到看起來像這樣的地方:
[{Post: 'post1', {Comment: 'comment1'}, {Comment: 'comment2'}}]
我嘗試使用 a.map并參考 theindex來檢查前一個Post是否與當前相同,Post如果它是.push我無法使用的前一個索引.map
這樣做的正確方法是什么?
uj5u.com熱心網友回復:
- 使用
Array#reduce, 迭代串列,同時更新 aMap,其中Post是鍵,值是物件,Post并Comments為Post - 使用
Map#values,您可以獲得分組物件的串列
const data = [ { Post: 'post1', Comment: 'comment1' }, { Post: 'post1', Comment: 'comment2' }, { Post: 'post1', Comment: 'comment3' }, { Post: 'post2', Comment: 'comment1' }, { Post: 'post2', Comment: 'comment2' }, { Post: 'post2', Comment: 'comment3' } ];
const res = [...
data.reduce((map, { Post, Comment }) => {
const { Comments = [] } = map.get(Post) ?? {};
map.set(Post, { Post, Comments: [...Comments, Comment] });
return map;
}, new Map)
.values()
];
console.log(res);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/496960.html
標籤:javascript 反应
