簡體   English   中英

使用相同鍵對數組元素進行分組 JSON JavaScript

[英]group elements of array with same key JSON JavaScript

不知道真正reduce的方法是怎樣的,我試過用這個獲取下一個JSON,但是顯然不行。

    {
        "w_elem": [
            {
                "item": [
                    {"type": "type_a","price": "100","discount": "10"},
                    {"type": "type_b","price": "120","discount": "12"},
                    {"type": "type_a","price": "165","discount": "10"}
                ],
                "user": "1001",
                "userType": "A"
            },
            {
                "item": [
                    {"type": "type_a","price": "85","discount": "5"},
                    {"type": "type_a","price": "15","discount": "0"}
                ],
                "user": "1002",
                "userType": "B"
            }
        ]
    }```

  w_elem.forEach(elem => {
    let user= elem.user;

    let aa = Object.values(elem.item.reduce((acc, {type, price, discount}) => {
      acc[type] = acc[type] || {type, price: 0, discount: 0, Count: 0};
      acc[type].price+= Number(price);
      acc[type].discount+= Number(discount);
      acc[type].Count += 1;
      return acc;
    },{}));
  });```

我試着做下一個

        {
            "user": "1001",
            "item": [
                {"type": "type_a","price": "265","discount": "20"},
                {"type": "type_b","price": "120","discount": "12"},
            ]
        },
        {
            "user": "1002",
            "item": [
                {"type": "type_a","price": "85","discount": "5"},
                {"type": "type_b","price": "15","discount": "0"}
            ]
        }
    ]

我不明白如何維護結構並且只使用 reduce 按類型對項目進行分組

嘗試這個:

let obj = {};
for(const element of data.w_elem){
    if(!obj[element.user]) obj[element.user] = element;
    else{
        obj[element.user].item.push(...element.item);
    }
}
data.w_elem = [...Object.keys(obj).map(e => obj[e])];

小提琴

暫無
暫無

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

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