用JS如何将JSON数据按类重新分类处理?

忆秋
  • 4
新手上路,请多包涵
 [    
        {
        "id":"0001",
        "name":"aa001",
        "value":"10",
        "group":"01"
        },    
        {
        "id":"0002",
        "name":"aa002",
        "value":"11",
        "group":"01"
        },    
        {
        "id":"0003",
        "name":"aa003",
        "value":"17",
        "group":"01"
        },    
        {
        "id":"0004",
        "name":"aa004",
        "value":"19",
        "group":"02"
        },    
        {
        "id":"0005",
        "name":"aa005",
        "value":"29",
        "group":"02"
        },    
        {
        "id":"0006",
        "name":"aa006",
        "value":"27",
        "group":"02"
        },
        "id":"0007",
        "name":"aa007",
        "value":"28",
        "group":"03"
        },    
        {
        "id":"0008",
        "name":"aa008",
        "value":"85",
        "group":"03"
        },
        "id":"0009",
        "name":"aa009",
        "value":"86",
        "group":"03"
        }
    ]
 [
        {
            ["aa001":
                {
                "id":"aa001"
                "aa001":"10"
                }],
                ["aa002":
                {
                "id":"aa002"
                "aa002":"11"
                }],
                ["aa003":
                {
                "id":"aa003"
                "aa003":"17"
                }
            ],
        },
        {
            [
                "aa004":
                {
                "id":"aa004"
                "aa004":"19"
                }],
                ["aa005":
                {
                "id":"aa005"
                "aa005":"29"
                }],
                ["aa006":
                {
                "id":"aa006"
                "aa006":"27"
                }
            ],
        },
        {
            [
                "aa007":
                {
                "id":"aa007"
                "aa007":"28"
                }],
                ["aa008":
                {
                "id":"aa008"
                "aa008":"85"
                }],
                ["aa009":
                {
                "id":"aa009"
                "aa009":"86"
                }
            ],
        }
    ]

想把上面的JSON数据按GROUP 分组输出成下面这种格式,请问用JS怎么操作呢,谢谢各位大神辣

回复
阅读 2.3k
2 个回答

随便写一个:

function handle(list) {
  const obj = {};
  list.forEach(item => {
    let { group, name, value } = item;
    let temp = {
      id: name,
      [name]: value,
    };
    if (obj[group]) {
      obj[group].push(temp);
    } else {
      obj[group] = [temp];
    }
  });
  return Object.values(obj).map(val => {
    return {
      [val[0].id]: val,
    };
  });
}
NicolasHe
  • 325
宣传栏