[英]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
与该属性的路径结合使用。 该函数返回路径的闭包,并重新调整一个函数,该函数采用一个对象来获取(嵌套)属性。
_.property(path)
返回一个函数,该函数将返回任何传入对象的指定属性。
path
可以指定为简单键,也可以指定为对象键或数组索引的数组,以进行深度属性获取。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.