Reputation: 285
I have following json as sample
var employee=[{sex:'M',id:1},{sex:'M',id:3},{sex:'f',id:4},{sex:'f',id:5}]
I want following array
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 };
});
How can I create array from object using specific criteria ?
_filter / _map they return whole object . I want only sex value .
Upvotes: 1
Views: 892
Reputation: 27976
First 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 on the partitioned data to get the 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>
Upvotes: 1