【问题标题】:Filtering object arrays based on uniqueValues根据 uniqueValues 过滤对象数组
【发布时间】:2020-02-10 17:37:07
【问题描述】:

我有一个需要过滤的对象数组。 对象结构如下:

[
    {
        name: 'Wheat',
        group: { name: 'Grains' }
    }, {
        name: 'Rice',
        group: { name: 'Grains' }
    }, {
        name: 'corn',
        group: { name: 'Grains' }
    }, {
        name: 'Oats',
        group: { name: 'Grains' }
    }, {
        name: 'Live Cattle',
        group: { name: 'Livestock/meat products' }
    }, {
        name: 'pork Bellies',
        group: { name: 'Livestock/meat products' }
    }
]

我需要这样的东西才能在 GUI 上显示它。 根据组名分离出数组。由于组名将是唯一的,但每个组可以在其下有多个选择。

所以我想创建一个 HashMap,其中键作为组名,值作为名称。 HashMap 如下所示:

{
    'Grains':                  'Oats',
    'Grains':                  'Wheat',
    'Grains':                  'corn',
    'Livestock/meat products': 'Live Cattle',
    'Livestock/meat products': 'pork Bellies'
}

如何使用数组函数来实现这一点,或者我需要有一个单独的逻辑来创建一个 HashMap?

谢谢,

【问题讨论】:

  • 你的哈希映射只能有一个同名的键。
  • 您的原始结构不是有效的对象。你不能有group: name: "Grains",你需要在每个键后面加上一个值。
  • 请使用真正的 JavaScript 对象结构更新您的帖子。您显示的不是有效的 JS 语法。
  • StackOverflow 不是免费的编码服务。你应该try to solve the problem first。请更新您的问题以在minimal reproducible example 中显示您已经尝试过的内容。如需更多信息,请参阅How to Ask,并拨打tour :)
  • 为什么Grains:Rice 不在预期结果中?删除它的过滤条件是什么?

标签: javascript arrays hashmap


【解决方案1】:

这是完美的方法。在调用此函数时传递您的数据。

function formatData(data) {
  const formattedData = {}
  data.forEach(({name, group}) => {
    formattedData[group.name] = formattedData[group.name] ? formattedData[group.name].concat(name) : [name];
  });
  return formattedData;
}

【讨论】:

    【解决方案2】:

    您不能生成具有重复键的 Map。所以你可以替换key和value然后就可以了,例如:

    const
      data = [
          {
              name: 'Wheat',
              group: { name: 'Grains' }
          }, {
              name: 'Rice',
              group: { name: 'Grains' }
          }, {
              name: 'corn',
              group: { name: 'Grains' }
          }, {
              name: 'Oats',
              group: { name: 'Grains' }
          }, {
              name: 'Live Cattle',
              group: { name: 'Livestock/meat products' }
          }, {
              name: 'pork Bellies',
              group: { name: 'Livestock/meat products' }
          }
      ],
      result = data.map(({ name, group }) => [name, group.name]),
      resultAsMap = new Map(result);
    

    或者,如果对您有帮助,您可以创建一组字符串,例如:

      result = new Set(data.map(({ name, group }) => `${group.name}: ${name}`));
    

    您还可以执行“分组依据”,这似乎更适合您的情况:

      reducer = (map, { name, group }) => map.set(group.name, (map.get(group.name) || []).concat(name)),
      result = data.reduce(reducer, new Map);
    

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 2018-12-25
      • 2018-07-06
      • 1970-01-01
      • 2020-12-03
      • 2020-12-14
      • 2020-08-15
      • 2021-04-03
      • 2020-03-06
      相关资源
      最近更新 更多