简体   繁体   中英

Plucking keys of nested objects with Lodash

I have a structure like this:

      areas = {
        'sample-id': {
          title: 'Area 1',
          type: 'outdoor',
          boundaries: [
            'fm-86071.92984676428', 'fm-33663.81255808968',
            'fm-22124.724922206497', 'fm-98002.82095021005'
          ]
        },
        'sample-id-2': {
          title: 'Area 2',
          type: 'meetingroom',
          boundaries: [
            'fm-39517.47084731459', 'fm-79087.74683350614',
            'fm-39153.28644344014', 'fm-38873.63204123109',
            'fm-67952.07827771583', 'fm-53210.58304837807',
          ]
        }
      };

I need to obtain an array consisting of all title keys of each area, ie, required output = ['Area 1', 'Area 2'] .
I found that _.pluck has been removed in favor of _.map , but using

_.map(areas, 'title')

..needs areas to be an array.
I also think that converting the object into an array using _.values and then using _.map ought to work, but is there any direct or preferred way ?
EDIT: I would also like to retain the order of keys
EDIT 2: Ok I forgot that there is NO ORDER for keys in objects, so leave that, I guess I'll use Array.prototype.sort()

在这种情况下,我使用

Object.keys(areas).map(k => areas[k].title)

Lodash's _.map() works on objects as well:

 var areas = {"sample-id":{"title":"Area 1","type":"outdoor","boundaries":["fm-86071.92984676428","fm-33663.81255808968","fm-22124.724922206497","fm-98002.82095021005"]},"sample-id-2":{"title":"Area 2","type":"meetingroom","boundaries":["fm-39517.47084731459","fm-79087.74683350614","fm-39153.28644344014","fm-38873.63204123109","fm-67952.07827771583","fm-53210.58304837807"]}}; var result = _.map(areas, 'title'); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

You can use Object.values() .

 areas = { 'sample-id': { title: 'Area 1', type: 'outdoor', boundaries: [ 'fm-86071.92984676428', 'fm-33663.81255808968', 'fm-22124.724922206497', 'fm-98002.82095021005' ] }, 'sample-id-2': { title: 'Area 2', type: 'meetingroom', boundaries: [ 'fm-39517.47084731459', 'fm-79087.74683350614', 'fm-39153.28644344014', 'fm-38873.63204123109', 'fm-67952.07827771583', 'fm-53210.58304837807', ] } }; let returnValue = Object.values(areas).map(value => value.title) console.log(returnValue) 

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