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

时间:2016-08-22 12:34:25

标签: underscore.js

我跟随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它们返回整个对象。我只想要性价值。

1 个答案:

答案 0 :(得分:1)

首先partition员工数据。这将返回一个包含2个数组的数组;第一个数组包含所有雄性,第二个数组包含雌性。然后在分区数据上使用pluck来获取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');

	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>