繁体   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