【記錄】Element表格動態表頭及數據

實現方式
一、取數據列表中第一條做爲表頭數據,再遍歷刪除不是表頭的固定屬性,結果賦值給一個空對象;
二、把處理好的數據遍歷 key 名 puah 進表頭配置數組中,事先在寫一個 key 名所對應的中文名方法返回中文名。數組

數據格式code

/*表格數據*/
const dataList = [
    {
        name: "李小龍",
        age: 24,
        city: "深圳",
        gender: "男",
        education: "本科",
        hobby: "武術"
    },
    {
        name: "黃飛鴻",
        age: 25,
        city: "深圳",
        gender: "男",
        education: "本科",
        hobby: "武術"
    },
    {
        name: "陳真",
        age: 26,
        city: "深圳",
        gender: "男",
        education: "本科",
        hobby: "武術"
    },
    {
        name: "霍元甲",
        age: 26,
        city: "深圳",
        gender: "男",
        education: "本科",
        hobby: "武術"
    },
]

/*表頭配置*/
const headConfig = {
    名字: "name",
    年齡: "age",
    性別: "gender"
}

實現方式1:刪除不是表頭配置的屬性orm

function extractData(data, config) {
    const formHead = Object.values(config)
    data.forEach((item, index) => {
        Object.keys(item).forEach(item2 => {
            if (!formHead.includes(item2)) delete data[index][item2];
        })
    })
    return data;
}

實現方式2:匹配表頭配置的屬性 push 進新數組返回對象

function extractData(data, config) {
    const formHead = Object.values(config)
    const arr = [],obj={};
    data.forEach((item, index) => {
        Object.entries(item).forEach(item2 => {
            if (formHead.includes(item2[0])) obj[item2[0]] = item2[1]
        })
        arr.push(obj)
    })
    return arr;
}

匹配對象中指定屬性ci

function mateData(data,config){
 const arr = []
 for (let [key, value] of Object.entries(config)) {
      if (data[key]) {
        arr.push({
          value: data[key],
          name: value
        });
      }
    }
    return arr;
  }
}
相關文章
相關標籤/搜索