Vue_取得不重複陣列(實作)

執行用途

希望在rawData裡,取出不重複的屬性名稱,為了將縣市名稱傳到選擇欄裡,供使用者選擇想知道的縣市資料,我們可使用Set.prototype.add()取出不重複的屬性名。

範例1:取出不重複值
1
2
3
var array = [1, 2, 2, 3, 3, 3];
var result = Array.from(new Set(array));
console.log(result); // [1, 2, 3]
範例2:取出不重複屬性名

注意:如果是以陣列包物件的形式進行new Set,回傳的雖然也是陣列的形式,不過裡頭會是字串的形式呈現,而非是陣列包物件。

1
2
3
var array = [{碗{....}}, {盤{....}} ,{碗{....}}];
var result = Array.from(new Set(array));
console.log(result); // ['碗', '盤'] 字串的形式

實作解析

目標是透過API取得的未整理資料,因為要在select上顯示各個區域的縣市,將經由new Set公式取得不重複的縣市,順利顯示在選單上,供使用者選取特定縣市。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
data: {
data: [],
locations: [],
},

methods: {
getUniqueList() {
const newlocations = new Set();
this.data.forEach((item, i) => {
newlocations.add(item.Region)
})
this.locations = Array.from(newlocations);
}
},

程式碼使用new Set( 含add())、forEach、array.from 多語法處理,需反覆理解。

  1. 新增變數newlocations並帶入new Set()語法
  2. 此時想取用data的區域資料,利用forEach執行全部的區域,並將取得資料add放入變數裡
  3. 此時將newlocation利用Array.from轉成陣列格式匯入到變數locations裡
  4. 變數location便取得區域名稱的唯一值

實作成品

作品: 口罩搜尋地圖