使用下划线从对象创建数组

create an array from object using underscore

我有以下 json 作为示例

var employee=[{sex:'M',id:1},{sex:'M',id:3},{sex:'f',id:4},{sex:'f',id:5}]

我想要跟随数组

maleIds=[1,3]
femaleIds=[4,5]

 var testFilter=_.filter(employee,function(obj) {
                return obj.sex=='M';
            });

            var testMap=_.map(testFilter, function(value, key){
                return { name : key, value : value };
            });

如何使用特定条件从对象创建数组?

_filter / _map 它们 return 整个对象。我只想要性价值。

首先partition the employee data. This will return an array of 2 arrays; the first array contains all the males and the second the females. Then use pluck在分区数据上获取ids:

var employee=[{sex:'M',id:1},{sex:'M',id:3},{sex:'f',id:4},{sex:'f',id:5}]

var partitions = _.partition(employee, {sex: 'M'})

var maleIds = _.pluck(partitions[0], 'id');
var femaleIds = _.pluck(partitions[1], 'id');

 var employee=[{sex:'M',id:1},{sex:'M',id:3},{sex:'f',id:4},{sex:'f',id:5}]

 var partitions = _.partition(employee, {sex: 'M'})

 var maleIds = _.pluck(partitions[0], 'id');
 var femaleIds = _.pluck(partitions[1], 'id');

document.getElementById('males').textContent = JSON.stringify(maleIds);
document.getElementById('females').textContent = JSON.stringify(femaleIds);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

<p>
  males <pre id="males"></pre>
  females <pre id="females"></pre>
</p>