我有跟随对象
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/