Search code examples
javascriptnestedlodash

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, i.e., 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()


Solution

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