Reputation: 17553
So I got this response from an API. I want to build a select box from all types, how do I extract only JSON related to skill_level from this JSON without using loops.
[
{
"id": 32,
"name": "Beginner",
"type": "skill_level"
},
{
"id": 33,
"name": "Intermediate",
"type": "skill_level"
},
{
"id": 34,
"name": "Experienced",
"type": "skill_level"
},
{
"id": 35,
"name": "Professional",
"type": "skill_level"
},
{
"id": 36,
"name": "Expert",
"type": "skill_level"
},
{
"id": 37,
"name": "Male",
"type": "sex"
},
{
"id": 38,
"name": "Female",
"type": "sex"
},
{
"id": 39,
"name": "Single",
"type": "marital_status"
},
{
"id": 40,
"name": "Married",
"type": "marital_status"
},
{
"id": 41,
"name": "Divorced",
"type": "marital_status"
},
{
"id": 42,
"name": "Not Wish To Say",
"type": "marital_status"
}
]
Upvotes: 1
Views: 89
Reputation: 17553
I just figured out that you can also do it this way in AngularJs:
<select id="sex" name="sex" ng-model="sex">
<option ng-repeat="option in $scope.data | filter:{type: 'sex'}" value="{{option.id}}">{{option.name}}</option>
</select>
Upvotes: 0
Reputation: 39659
Check out Array.prototype.filter
:
var skillLevels = data.filter(function(item) {
return item.type === 'skill_level';
});
From the docs, this works as follows:
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Assuming that data
refers to the array you provided in your question, this will result with skillLevels
being a new array containing all of the items where item.type
was equal to "skill_level"
.
Upvotes: 3
Reputation: 4480
You can do this with lodash:
$scope.data = ...;
$scope.filtered = _.filter($scope.data, { 'type': 'skill_level' });
This will return only the objects that have skill_level
for type
.
Upvotes: 1