JavaScript:將CSV字串檔案轉換為二維物件陣列


CSV是逗號分隔值,儲存在副檔名為.csv的檔案中。這允許使用者以表格或電子表格格式儲存資料。

在本文中,我們將探討如何將CSV字串的資料轉換為二維物件陣列,其中字串的第一行定義檔案標題。我們將首先讀取這一行,然後將其餘值與之對映。

我們將使用以下函式,該函式將充當陣列和字串的原型函式,因為它在讀取檔案後對映資料時將很有幫助。

indexOf 函式

String.prototype.indexOf() 函式返回此引數字串第一次出現的第一個索引。返回的值為基於0的索引,如果此型別的字串不存在,則返回-1。

例如

str = 'How are you?'
str.indexOf('a');

輸出

4

Slice 函式

此方法返回一個新陣列,其中包含實現它的陣列的一部分,並且原始陣列將保持不變。

例如

['a','b','c','d'].slice(1)

輸出

['b','c','d']

Map 函式

此方法在對每個元素呼叫提供的函式後返回一個新陣列。

例如

arr = [2, 4, 8, 16]
newArr = arr.map( item => item/2) //Dividing every number by 2

輸出

[1, 2, 4, 8]

Split 函式

此方法用於將給定字串拆分為字串陣列。透過使用引數中提供的指定分隔符,將字串分隔成多個子字串。

例如

str = 'Tutorials Point'
arr = str.split(' ');

輸出

[‘Tutorials’, ‘Point’]

Reduce 函式

JavaScript 中的此方法用於將陣列縮減為單個值,該值對陣列的每個元素從左到右執行提供的函式,並返回函式的值。此值儲存在累加器中。

例如

arr = [2,4,6,8]
arr.reduce(function(accumulator,currentValue){
   return accumulator+currentValue;
},0)

輸出

20

方法

  • 我們將使用 JavaScript slice() 方法提取字串的部分並將其提取的部分返回到一個新的字串,以“
    ”作為第一次出現。

  • 資料值使用“
    ”作為分隔符儲存。

  • 我們將遍歷所有值,然後在陣列末尾對映每個值。

  • “storeKeyValue”變數將用於儲存每個鍵及其相應的值。

示例 1

在下面的示例中,我們將 CSV 字串中的值對映到二維物件陣列。

# index.html

<!DOCTYPE html>
<html>
<head>
   <title></title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      function CSVstring_to_Array(data, delimiter = ',') {
         /* Collecting the titles */
         const titles = data.slice(0, data
            .indexOf('
')).split(delimiter);                /* Storing the value of each cell*/          const titleValues = data.slice(data             .indexOf('
') + 1).split('
');                /* Mapping these values with the title */          const ansArray = titleValues.map(function (v) {              /* Values variable will store individual             title values*/             const values = v.split(delimiter);                       /* storeKeyValue variable will store             object containing each title             with their respective values*/             const storeKeyValue = titles.reduce(                function (obj, title, index) {                   obj[title] = values[index];                   return obj;                }, {});             return storeKeyValue;          });          return ansArray;       };       var inputString1 = "Name,EmpId, Salary
Steve,001,50000
Bill,002,60000";       console.log(CSVstring_to_Array(inputString1));       var inputString2 = "ProductName,Price,Category      
Smartphone,10000,Electronics
Face       Cream,500,Beauty
Shoes,2000,Footwear";       console.log(CSVstring_to_Array(inputString2,';'));    </script> </body> </html>

輸出

在成功執行上述程式後,瀏覽器將顯示以下結果:

Welcome To Tutorials Point

在控制檯中,您將找到所有計算結果,請參見下面的螢幕截圖:

更新於: 2022-04-22

637 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告