简体   繁体   中英

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

 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.

It's working for me:

 let groups = _.groupBy(this.cars, car => car.location.city);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM