【问题标题】:Group array of objects by 1 key, and split 1 attribute按 1 个键对对象数组进行分组,并拆分 1 个属性
【发布时间】:2021-05-21 11:30:38
【问题描述】:

我有这个对象数组

test = [
    {
        'id': 1,
        'name': 'XYZ'
        'value': 10
        'quantity': 100
    }, 
    {
        'id': 1,
        'name': 'XYZ'
        'value': 20
        'quantity': 200
    }, 
    {
        'id': 2,
        'name': 'ABC'
        'value': 11
        'quantity': 111
    }, 
    {
        'id': 2,
        'name': 'ABC'
        'value': 22
        'quantity': 222
    }
]

我想按 id 对它们进行分组,但名称和 {value, quantity} 分开,如下所示:

result = {
    1: [
        'name': 'XYZ'
        'items': [
            {
                'value': 10
                'quantity': 100
            },
            {
                'value': 20
                'quantity': 200
            }
        ]
    ], 
    2: [
        'name': 'ABC'
        'items': [
            {
                'value': 11
                'quantity': 111
            },
            {
                'value': 22
                'quantity': 222
            }
        ]
    ], 
}

知道我该怎么做吗?我可以按 id 分组,但我无法提取名称。 谢谢

【问题讨论】:

  • 请添加您的代码。
  • id 和 name 总是相关的吗?即,是否不可能出现 id 为 1 的项目(例如)名称为 XYZ 而另一个项目的 id 为 1 且名称为 UIO 的情况?
  • 12 应该是 object
  • @BenStephens 是的,它们总是相关的,问题是我需要两个值

标签: javascript arrays json group-by


【解决方案1】:

我认为您可以在这种情况下使用reduce() 将元素按id 分组

const test = [
    {
        'id': 1,
        'name': 'XYZ',
        'value': 10,
        'quantity': 100,
    }, 
    {
        'id': 1,
        'name': 'XYZ',
        'value': 20,
        'quantity': 200,
    }, 
    {
        'id': 2,
        'name': 'ABC',
        'value': 11,
        'quantity': 111,
    }, 
    {
        'id': 2,
        'name': 'ABC',
        'value': 22,
        'quantity': 222,
    }
];

const res = test.reduce((ac, {id, name, ...rest}) => ({...ac, [id]: ac[id] ? [...ac[id], rest] : [rest] }), {});
console.log(res)

【讨论】:

  • 输出中缺少名称属性
【解决方案2】:

您可以使用reduce轻松实现此结果

const arr = [
  {
    id: 1,
    name: "XYZ",
    value: 10,
    quantity: 100,
  },
  {
    id: 1,
    name: "XYZ",
    value: 20,
    quantity: 200,
  },
  {
    id: 2,
    name: "ABC",
    value: 11,
    quantity: 111,
  },
  {
    id: 2,
    name: "ABC",
    value: 22,
    quantity: 222,
  },
];

const result = arr.reduce((acc, curr) => {
  const { id, name, value, quantity } = curr;
  if (acc[id]) {
    acc[id].items.push({ value, quantity });
  } else {
    acc[id] = {
      name,
      items: [{ value, quantity }],
    };
  }
  return acc;
}, {});

console.log(result);

【讨论】:

    【解决方案3】:

    您可以使用foreach 来获得您需要的东西:

    test = [
        {
            id: 1,
            name: 'XYZ',
            value: 10,
            quantity: 100,
        }, 
        {
            id: 1,
            name: 'XYZ',
            value: 20,
            quantity: 200,
        }, 
        {
            id: 2,
            name: 'ABC',
            value: 11,
            quantity: 111,
        }, 
        {
            id: 2,
            name: 'ABC',
            value: 22,
            quantity: 222,
        }
    ];
    
    res = {};
    
    test.forEach(el => {
        let key = el.id;
        if (!res.hasOwnProperty(key)) {
            res[key] = {
                name: el.name,
                items: []
            };
        }
        res[key].items.push({value: el.value, quantity: el.quantity});
    });
    
    console.log(res);

    【讨论】:

      【解决方案4】:

      您可以将destructuring 用于idname,并将对象的其余部分 (Rest in Object Destructuring ...) 设置为item

      如果不存在,则为属性id 分配一个新对象,并将item 推送到组的items 数组中。

      const
          data = [{ id: 1, name: 'XYZ', value: 10, quantity: 100 }, { id: 1, name: 'XYZ', value: 20, quantity: 200 }, { id: 2, name: 'ABC', value: 11, quantity: 111 }, { id: 2, name: 'ABC', value: 22, quantity: 222 }],
          result = data.reduce((r, { id, name, ...item }) => {
              r[id] ??= { name, items: [] };
              r[id].items.push(item);
              return r;
          }, {});
      
      console.log(result);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        猜你喜欢
        • 2018-08-01
        • 2019-04-15
        • 2023-02-07
        • 2018-08-28
        • 1970-01-01
        • 2015-12-31
        • 2021-11-25
        • 2019-12-28
        • 1970-01-01
        相关资源
        最近更新 更多