当属性在另一个对象中时如何将 _.groupBy js 用于组对象 - TypeScript

How to use _.groupBy js for group object when the properties is in another object - TypeScript

我有关注对象

var cars = [
 {
    'make': 'audi',
    'model': 'r8',
    'year': '2012',
    location: {
       'city': 'A',
       'state': 'X',
       'country': XX'
    }
}, {
    'make': 'audi',
    'model': 'rs5',
    'year': '2013',
    location: {
       'city': 'D',
       'state': 'X',
       'country': XX'
    }
}, {
    'make': 'ford',
    'model': 'mustang',
    'year': '2012',
    location: {
      'city': 'A',
      'state': 'X',
      'country': XX'
    }
}, {
    'make': 'ford',
    'model': 'fusion',
    'year': '2015',
    location: {
      'city': 'A',
      'state': 'X',
      'country': XX'
    }
}, {
    'make': 'kia',
    'model': 'optima',
    'year': '2012',
    location: {
      'city': 'C',
      'state': 'X',
      'country': XX'
    }
},

];

我要按城市拼车

所以我正在使用下划线 js,但我不知道如何访问 属性 中的其他对象。我正在尝试这样做,但没有用。

var groups = _.groupBy(cars, 'location.city');

你能帮帮我吗?

谢谢

您可以使用 _.property 和 属性 的路径进行分组。此函数 returns 路径上的闭包并返回一个函数,该函数采用一个对象来获取(嵌套的)属性。

_.property(path)

Returns a function that will return the specified property of any passed-in object. path may be specified as a simple key, or as an array of object keys or array indexes, for deep property fetching.

var cars = [{ make: 'audi', model: 'r8', year: '2012', location: { city: 'A', state: 'X', country: 'XX' } }, { make: 'audi', model: 'rs5', year: '2013', location: { city: 'A', state: 'X', country: 'XX' } }, { make: 'ford', model: 'mustang', year: '2012', location: { city: 'C', state: 'X', country: 'XX' } }, { make: 'ford', model: 'fusion', year: '2015', location: { city: 'B', state: 'X', country: 'XX' } }, { make: 'kia', model: 'optima', year: '2012', location: { city: 'A', state: 'X', country: 'XX' } }],
    groups = _.groupBy(cars, _.property(['location', 'city']));

console.log(groups);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

Nina 的回答对于 javascript 实现是正确的,但我需要使用打字稿来完成,所以,我为我的问题提供了一个解决方案。

它对我有用:

 let groups = _.groupBy(this.cars, car => car.location.city);