簡體   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