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

标签 javascript angular typescript underscore.js

我有跟随对象

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带有用于分组的属性的路径。此函数返回路径上的闭包并返回一个函数,该函数采用一个对象来获取(嵌套)属性。

_.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>

关于javascript - 当属性位于另一个对象中时如何将 _.groupBy js 用于组对象 - TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53414278/

相关文章:

javascript - Typescript 错误 : Map. values() 给出 IterableIterator not Iterable

javascript - 无法使用 ExtDnd5 对节点进行排序,只能设置为子节点

javascript - 我无法使用 Angular2 从 JSONP 响应中获取正文数据,但它可以通过使用 ajax 来工作

javascript - 带有来自 Typescript 的路径的 Monorepo 不起作用

javascript - Ajax 调用第二次不起作用

javascript - 用于验证信用卡对账单的对账单描述符的正则表达式

angular - 在 Angular 6 中实现 Paypal

angular - @agm/core 和 @angular/google-maps 谷歌地图有什么区别

typescript - 基于部分文本删除行的 Office 脚本

javascript - 如何在 Angular 2+ 模板中使用 isArray()?