使用Lodash采集嵌套对象的键

时间:2017-11-09 04:57:51

标签: javascript nested lodash

我有这样的结构:

      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',
          ]
        }
      };

我需要获取一个由每个区域的所有title个键组成的数组,即必需的输出= ['Area 1', 'Area 2']
我发现_.pluck已被移除,转而使用_.map,但使用

_.map(areas, 'title')

..需要区域为阵列 我还认为使用_.values将对象转换为数组然后使用_.map应该可以工作,但有没有直接或首选方式?
编辑:我还想保留按键的顺序
编辑2:好的,我忘了对象中的键有 NO ORDER ,所以请保留,我想我会使用Array.prototype.sort()

3 个答案:

答案 0 :(得分:1)

在这种情况下,我使用

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

答案 1 :(得分:1)

Lodash的_.map()也适用于对象:



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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用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)