簡體   English   中英

我將如何循環遍歷此數組並根據 Regex 呈現表格?

[英]How would I loop through this array and render a table based on Regex?

我正在構建一個 chrome 擴展程序,它可以獲取成分表並將其與數據集進行比較。因為大多數營養表都有一個類名“營養”,所以我通過它們的類名來獲取。 這就是我得到的:

["\tPer 100g\tPer 35g Ball\nEnergy\t449kcal\t157kcal\nFat\t24.4g\t8.6g\nSaturated fat\t4.5g\t1.6g\nMonounsaturated fat\t13.6g\t4.8g\nPolyunsaturated fat\t5.2g\t1.8g\nTotal Carbohydrates\t31.0g\t10.9g\nSugars\t19.7g\t6.9g\nFibre\t6.1g\t2.1g\nProtein\t23.1g\t8.1g\nSalt\t0.71g\t0.25"]

我需要遍歷這個數組並以這種格式返回它: 在此處輸入圖像描述

我在考慮使用 Regex 來拆分劑量(所以是單詞)和數字?

正則表達式對此來說太過分了。 您可以簡單地拆分字符串,然后將它們 map 轉換為更適合您使用的格式。

 const input = "\tPer 100g\tPer 35g Ball\nEnergy\t449kcal\t157kcal\nFat\t24.4g\t8.6g\nSaturated fat\t4.5g\t1.6g\nMonounsaturated fat\t13.6g\t4.8g\nPolyunsaturated fat\t5.2g\t1.8g\nTotal Carbohydrates\t31.0g\t10.9g\nSugars\t19.7g\t6.9g\nFibre\t6.1g\t2.1g\nProtein\t23.1g\t8.1g\nSalt\t0.71g\t0.25"; // First, we split the input on each line. const data = input.split('\n') // We then skip the first row, since it only contains labels and not data. .slice(1) // We then map the individual data rows to objects. .map(row => { // We destructure the split array based on the format we expect the data to be in. const [nutrient, per100, per35] = row.split('\t'); // We bundle the destructured data into a new object and return it. return { nutrient, per100, per35 }; }); console.log(data);

這會將您的輸入整齊地格式化為具有屬性nutrientper100per35的對象數組,然后您可以使用這些對象從中生成表格的 HTML 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM