[英]How to use _.groupBy js for group object when the properties is in another object - TypeScript
I have the follow object 我有以下对象
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'
}
},
]; ]。
I would like group cars by city. 我想要按城市分组的车。
So I'm using underscore js, but I don't know how can I access other object in property. 所以我正在使用下划线js,但是我不知道如何访问属性中的其他对象。 I'm trying do it, but not working.
我正在尝试做,但是没有用。
var groups = _.groupBy(cars, 'location.city');
could you please help me? 请你帮助我好吗?
thanks 谢谢
You could use _.property
with a path to the property for grouping. 您可以将
_.property
与该属性的路径结合使用。 This function returns a closure over the path and retuns a function which takes an object for getting the (nested) 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.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>
The Nina's answer is correct for javascript implementation , but I need do it using typescript, so, I fund one solution for me question. Nina的答案对于javascript实现是正确的,但是我需要使用打字稿来实现,因此,我为我的问题提供了一种解决方案。
It's working for me: 它为我工作:
let groups = _.groupBy(this.cars, car => car.location.city);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.