[英]Sorting/Filtering JSON based on certain property
所以我从API得到了这个响应。 我想从所有类型构建一个选择框,如何在不使用循环的情况下仅从此JSON中提取与skill_level相关的JSON。
[
{
"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"
}
]
Array.prototype.filter
出Array.prototype.filter
:
var skillLevels = data.filter(function(item) {
return item.type === 'skill_level';
});
从文档来看,这如下:
filter()方法创建一个新数组,其中所有元素都通过了由提供的函数实现的测试。
假设data
是指你在你的问题中提供的阵列,这将导致与skillLevels
是包含所有在项目的新的阵列item.type
等于"skill_level"
。
我刚刚发现您也可以在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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.