2020年9月4日 星期五

陣列的再處理,以 Vue filter為例

<template>
  <div class="container">
<button type="button" @click="newarrayproduct">test</button>
 </div>
</template>

先做一個按鈕觸發條件作為測試用。

<script>
export default {
  data () {
    return {   
      products: [],
      newproduct:[],  
    };
  },
   created () {
    this.getProducts()
  },
  methods: {
    newarrayproduct(){
      this.newproduct = this.products;
      const salad = this.newproduct.filter(function(item, index, array){
        return item.category == '沙拉';
      });
      this.newproduct = salad;
      console.log(this.newproduct);
    },
  }
</script>


created 是起始從 API 先抓取要處理的陣列,在此非重點所以省去函式內容。

data 中應先定義要處理的資料內容,還沒載入實質內容所以用空的就好。


今天的故事是:餐廳裡有很多諸如前菜、主餐、套餐、甜點...等,在頁面呈現的時候如果只依序會很雜亂,並無法讓顧客找到最心儀的餐點,因此以沙拉為例如何用 JS 方法將"所有沙拉"從"所有餐點"中取出來。

一、methods 內寫要處理的函式,首先先複製原本產品內容到新的陣列上。


         this.newproduct = this.products;


二、定義一個變數

        const salad 


三、指向要處理的陣列

        this.newproduct


四、利用 filter 抓出資料內建的 category , category 內有沙拉、湯、主餐...等等分類

        .filter(function(item, index, array){
        return item.category == '沙拉';
      });

    經過處理之後 salad 內容就是所有沙拉形成的陣列。


五、要處理的陣列賦予結果的值

        this.newproduct = salad;

        這樣 newproduct 陣列裡就會有所有沙拉分類的菜,同理也可以處理金額 > x ...等等

        常見的分類方式,只要改 return 後面就好。


參考資料:

https://wcc723.github.io/javascript/2017/06/29/es6-native-array/

https://cn.vuejs.org/v2/guide/list.html


沒有留言:

張貼留言