[英]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.