使用jquery从数组中获取唯一数据

时间:2018-05-28 17:26:51

标签: javascript jquery arrays

我从包含大量数据的大型API中获取数据。我需要输出大量具有相同构建名称的数据,但我不希望所有数据都重复出现我只想显示唯一数据。

我该如何做到这一点?

var data = {
    "data": [{
        "id": 1,
        "building": "Big Building"
    }, {
        "id": 2,
        "building": "Big Building"
    }, {
        "id": 3,
        "building": "Small Building"
    }, {
        "id": 4,
        "building": "Small Building"
    }]
}

jQuery.each(data.data, function(index, item) {
    console.log(this['building']);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

结果:

Big Building
Big Building
Small Building
Small Building

通缉结果:

Big Building
Small Building

3 个答案:

答案 0 :(得分:2)

您可以使用new Set获取唯一值。使用map重复数组。

let data = {
  "data": [{"id": 1,"building": "Big Building"},
    {"id": 2,"building": "Big Building"},
    {"id": 3,"building": "Small Building"},
    {"id": 4,"building": "Small Building"}]
};

let result = [...new Set(data.data.map(o => o.building))];

console.log( result );

答案 1 :(得分:0)

只使用javascript,使用数组reduce方法&amp;可以实现相同的结果。使用indexOf

var apiData = {
  "data": [{
      "id": 1,
      "building": "Big Building"
    },
    {
      "id": 2,
      "building": "Big Building"
    },
    {
      "id": 3,
      "building": "Small Building"
    },
    {
      "id": 4,
      "building": "Small Building"
    }
  ]
}

var unq = apiData.data.reduce(function(acc, curr) {
  // here acc is the empty array which is passed as thisArg
  // indexOf to check if the array contains the building name
  if (acc.indexOf(curr.building) === -1) {
    acc.push(curr.building)
  }
  return acc;

}, [])

console.log(unq)

答案 2 :(得分:0)

var response = {
"data": [
  {
     "id": 1,
     "building": "Big Building"
  },
  {
     "id": 2,
     "building": "Big Building"
  },
  {
     "id": 3,
     "building": "Small Building"
  },
  {
     "id": 4,
     "building": "Small Building"
  }
]};

var buildingArray = [];
var uniqueResponse = [];
for(i = 0; i< response.data.length; i++){    
    if(buildingArray.indexOf(response.data[i].building) === -1){
        uniqueResponse.push(response.data[i]);  
        buildingArray.push(response.data[i].building);
    }        
}
console.log(uniqueResponse);