首页 > 解决方案 > 使用 groupBy 时向 JS 中的对象添加值

问题描述

当两个项目相同时,我正在使用mapValuesandgroupBy进行分组和创建。keystypeId

例如原始数据是

{
    "Name": "One",
    "typeId": 1
},
{
    "Name": "Two",
    "typeId": 2
},
{
    "Name": "One Two",
    "typeId": 1
},
{
    "Name": "Three",
    "typeId": 3
},
{
    "Name": "Three Two",
    "typeId": 3
}

并通过使用groupBy我将具有匹配项的对象typeId和来自“对象”omittypeId值分组为...

const GroupedTypes = Object.entries(
   _.mapValues(_.groupBy(data, 'typeID'), rlist =>
      rlist.map(type => _.omit(type, 'typeID'))
   )
);

按预期返回...

[
    "1",
    [
      {
        "Name": "One",
      },
      {
        "Name": "One Two",
      }
    ]
  ],
  [
    "2",
    [
      {
        "Name": "Two",
      }
    ]
  ],
  [
    "3",
    [
      {
        "Name": "Three",
      }
    ],
    [
      {
        "Name": "Three Two",
      }
    ]
]

但是,我还想从第一个对象中Name的值添加Name一个0对象。因此以类似的东西结束。

[
    "1",
    "One",
    [
      {
        "Name": "One",
      },
      {
        "Name": "One Two",
      }
    ]
],
[
    "2",
    "Two",
    [
      {
        "Name": "Two",
      }
    ]
],
[
    "3",
    "Three",
    [
      {
        "Name": "Three",
      }
    ],
    [
      {
        "Name": "Three Two",
      }
    ]
]

我一直在查看lodash文档,但找不到有效的方法。我怎样才能做到这一点?

标签: javascriptarraysobjectecmascript-6lodash

解决方案


您可以reduce根据以下内容对项目进行分组typeId

const input=[{"Name":"One","typeId":1},{"Name":"Two","typeId":2},{"Name":"One Two","typeId":1},{"Name":"Three","typeId":3},{"Name":"Three Two","typeId":3}]

const merged = input.reduce((acc, { Name, typeId }) => {
  acc[typeId] = acc[typeId] || [ typeId, Name, []];
  acc[typeId][2].push({ Name });
  return acc;
}, {})

console.log(Object.values(merged))

您需要创建一个累加器对象,每个对象都typeId作为键,输出中需要的数组作为其值。如果该键尚不存在,请将该键添加[ typeId, Name, []]为值。这样,第一项Name将在输出中。这是 accumulator/ 的merged样子:

{
      "1": [1, "One", [{ "Name": "One" }, { "Name": "One Two" }]],
      "2": [2, "Two", [{ "Name": "Two" }]],
      "3": [3, "Three", [{ "Name": "Three" }, { "Name": "Three Two" }]]
}

然后使用,Object.values()来获取这个对象的值作为一个数组


推荐阅读