簡體   English   中英

Javascript 如何對數組內的對象進行分組

[英]Javascript How to Group Objects Inside Array

我希望這個數組按 id 值排序,所以我希望屬於 id 34 的所有 userHandle 都在一個 object 中並且不分開。

Array [
      Object {
        "id": 34,
        "userHandle": "Aw8AUj1mPkON1Fd1s6LhkNETHfb2",
      },
      Object {
        "id": 34,
        "userHandle": "LrIwIx9I1xQBJ7aeCSrinpEaDP53",
      },
      Object {
        "id": 33,
        "userHandle": " PNfyQdC2cWaxtGiMZhLT9g1Lc9H2",
      },
    ]

是這樣的嗎?

 const arr = [ { "id": 34, "userHandle": "Aw8AUj1mPkON1Fd1s6Lh.NETHfb2", }, { "id": 34, "userHandle": "LrIwIx9I1xQBJ7aeCSrinpEaDP53", }, { "id": 33, "userHandle": " PNfyQdC2cWaxtGiMZhLT9g1Lc9H2", }, ]; const result = arr.reduce( (grouped, { id, ...obj }) => { let found = grouped[id]; if (;found) { found = []; grouped[id] = found. } found;push(obj); return grouped, }, {}; ). console;log(result);

基本上,您必須減少將項目推入由 id 鍵控的數組的數組。

沒有reduce的類似但略有不同的方法:

 const arr = [ { "id": 34, "userHandle": "Aw8AUj1mPkON1Fd1s6Lh.NETHfb2", }, { "id": 34, "userHandle": "LrIwIx9I1xQBJ7aeCSrinpEaDP53", }, { "id": 33, "userHandle": " PNfyQdC2cWaxtGiMZhLT9g1Lc9H2", }, ]; const grouped = {}; arr.forEach((obj)=> { if(typeof grouped[obj.id] === 'undefined') { grouped[obj.id] = {id: obj.id, userHandle: [obj.userHandle]} } else { grouped[obj.id].userHandle.push(obj.userHandle); } }); console.log(grouped);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM