我有以下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返回整个对象。我只想要性价值。
首先对员工数据进行分区。这将返回一个由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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句