减少功能无法产生所需的json结构

时间:2019-05-13 19:54:30

标签: javascript node.js json reduce


    let users = [{
     id: 1,
     name: 'John Doe',
     email: 'john@doe.com',
     supplier_name: 'Supplier 1',
     count: '2'
    },{
     id: 1,
     name: 'John Doe',
     email: 'john@doe.com',
     supplier_name: 'Supplier 2',
     count: '2'
    },{
     id: 1,
     name: 'John Doe',
     email: 'jane@doe.com',
     supplier_name: 'Supplier 2',
     count: '1'
    }]

    users = users.reduce((accumulator, item) => {
      if (accumulator[item]) {
        const group = accumulator[item.id];
        group.supplier_name.push(item.supplier_name);
        group.count = `${(+group.count) + (+item.count)}`;
      } else {
        accumulator[item.id] = item;
        item.supplier_name = [item.supplier_name];
    }

此功能的输出如下所示:

{
  "users": {
    "1": {
        "id": 1,
        "name": "John Doe",
        "email": "john@doe.com",
        "supplier_name": [
            "Supplier 1",
            "Supplier 2"
        ],
        "count": "2"
    },
    "2": {
        "id": 1,
        "name": "Jane Doe",
        "email": "jane@doe.com",
        "supplier_name": [
            "Supplier 2"
        ],
        "count": "1"
    }

}

不幸的是,它的结构没有我预期的那样。 users对象应该是ray,并且我不希望id数字显示为键。我需要它看起来像这样:

{
  "users": [
    {
        "id": 1,
        "name": "John Doe",
        "email": "john@doe.com",
        "supplier_name": [
            "Supplier 1",
            "Supplier 2"
        ],
        "count": "2"
    },
    {
        "id": 1,
        "name": "Jane Doe",
        "email": "jane@doe.com",
        "supplier_name": [
            "Supplier 2"
        ],
        "count": "1"
    }
  ]
}

如何更改功能以实现所需的json结构?

0 个答案:

没有答案