从现有数组中简化和排序新数组的创建

飘过

我有一个像这样的对象数组:

[
   {country: 'a', region: 1}
   {country: 'a', region: 2}
   {country: 'a', region: 3}
   {country: 'b', region: 4}
   {country: 'b', region: 5}
   {country: 'c', region: 6}
   {country: 'd', region: 7}
   {country: 'e', region: 8}
]

我想以这样的数组结束:

[
   {country: 'a', region: [1, 2, 3]}
   {country: 'b', region: [4, 5]}
   {country: 'c', region: [6]}
   {country: 'd', region: [7]}
   {country: 'e', region: [8]}
]

我一直在尝试以下操作,但我被困在我想将结果推送到现有 byCountry 数组中的部分...

另外我觉得 filter 可能不是最好的功能,它可能比我编写它的方式简单得多。

 let byCountry = []

    regions.forEach( (region) => {
      const filter = byCountry.filter( country => country.country === region.country )

      if (filter.length > 0) {
        const filteredCountry = filter[0]['country']
        const result = _.find(byCountry, country => {
          return country.country === filteredCountry
        })
// stuck here

      } else {
        const newCountry = {
          country: region.country,
          regions: [region.region],
        }

        byCountry.push(newCountry)
      }
    })
吓人的

您可以将数组转换为将国家/地区映射到多个区域的哈希图,{<country>: Array<regions>}然后将其转换回数组:

const records = [
      {country: 'a', region: 1},
      {country: 'a', region: 2},
      {country: 'a', region: 3},
      {country: 'b', region: 4},
      {country: 'b', region: 5},
      {country: 'c', region: 6},
      {country: 'd', region: 7},
      {country: 'e', region: 8}
    ];

const regionsByCountry = new Map();

records.forEach(record => {
  if (!regionsByCountry.has(record.country)) {
    regionsByCountry.set(record.country, []);
  }

  regionsByCountry.get(record.country).push(record.region);
});

const merged = Array.from(regionsByCountry)
                    .map(([country, region]) => ({country,region}));
                    
console.log(merged)

您可以使用Map具有可读 API的现代语言也可以使用普通对象文字{}

地图文档:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

从Ruby中的现有数组创建新数组

从php中的现有数组创建新数组

从现有数组和对象创建新对象

如何使用现有数组的元素创建新数组?

从现有数组属性创建新数组

使用.map和.filter过滤现有数组以创建新的过滤后的数组

如何使用 TypeScript 中现有数组中的选定元素创建新数组?

在foreach中的每个循环中,在现有数组中创建新数组

在现有数组中的数组中添加新对象

如何从 SwiftUI View Init 中的现有数组创建新数组

分组并统计现有数组中的数据以创建新的重组数组

从现有数组中创建一个新数组

使用现有数组中的唯一值创建新数组

如何从现有数组中创建嵌套数组

向JavaScript中的现有数组添加新值

向JavaScript中的现有数组添加新值

根据ruby中现有数组中元素之间的关系创建一个新数组

使用JS中现有数组的一些值创建一个新数组

在现有数组上创建分页

从现有数组创建HTML表

在现有数组中添加额外的元素和值

如何对特定值进行排序并从现有的 PHP 中创建新的数组对象?

在现有数组中添加新数组时数组形成不正确

如何在不复制数组的情况下创建对现有数组的新引用

通过将新元素插入现有数组来创建新数组

仅使用包含特定值的元素从现有数组创建新数组

从特定索引处的现有数组创建一个新数组

基于现有数组创建一个新的数组对象

从现有对象数组创建新数组