在JS中归约分组

时间:2018-09-23 18:10:27

标签: javascript arrays reduce

是否可以使用array.reduce方法按“国家”对它们进行分组? 任何建议表示赞赏。

const table = { 
  0: {
    firstName: 'Mark',
    lastName: 'Spencer',
    adress: {
      Country: 'England',
      Town:    'London',
      Street: 'Old street',
      Postcode: 'W2 1RB'
    }
  },
  1: {
    firstName: 'Franz',
    lastName: 'Muller',
    adress: {
      Country: 'Germany',
      Town: 'Berlin'
      Street: 'Wilhelmstrasse',
      Postcode: '10115 - 14199'
    }
  },
  2: {
    firstName: 'William',
    lastName: 'Davies',
    adress: {
      Country: 'England',
      Town:    'Liverpool'
      Street: 'New Street',
      Postcode: 'l1 0au'
    }

如何仅使用此方法对它们进行正确排序?

2 个答案:

答案 0 :(得分:0)

您可以将带有诸如Object.assign的索引之类的键的对象转换为数组,然后缩小它。

var data = { 0: { firstName: 'Mark', lastName: 'Spencer', address: { Country: 'England', Town: 'London', Street: 'Old street', Postcode: 'W2 1RB' } }, 1: { firstName: 'Franz', lastName: 'Muller', address: { Country: 'Germany', Town: 'Berlin', Street: 'Wilhelmstrasse', Postcode: '10115 - 14199' } }, 2: { firstName: 'William', lastName: 'Davies', address: { Country: 'England', Town: 'Liverpool', Street: 'New Street', Postcode: 'l1 0au' } } },
    grouped = Object
        .assign([], data)
        .reduce((r, o) => {
            var key = o.address.Country;
            (r[key] = r[key] || []).push(o);
            return r;
        }, Object.create(null));
    
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您可以使用conn = pymongo.MongoClient('localhost') # replace localhost with the real address db = conn['db_name'] db['collection_name'].insert_one({'x': 1}) # replace {'x': 1} with `customer` 以数组的形式获取对象的值。桌子上的钥匙似乎没有什么意义。它们只是索引。这是您要分组的值:使用Object.values可以使您清楚。

一旦有了数组,就可以使用Object.values。我将Array.prototype.reduce包装在内部使用groupBy的可重用函数中。

reduce