繁体   English   中英

根据某些属性对JSON进行排序/过滤

[英]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.filterArray.prototype.filter

var skillLevels = data.filter(function(item) {
    return item.type === 'skill_level';
});

从文档来看,这如下:

filter()方法创建一个新数组,其中所有元素都通过了由提供的函数实现的测试。

假设data是指你在你的问题中提供的阵列,这将导致与skillLevels是包含所有在项目的新的阵列item.type等于"skill_level"

您可以使用lodash做到这一点

$scope.data = ...;
$scope.filtered = _.filter($scope.data, { 'type': 'skill_level' });

这只会返回typeskill_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM