简体   繁体   English

我将如何循环遍历此数组并根据 Regex 呈现表格?

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

Im building a chrome extension that grabs a table of ingredients and compares it with a dataset.Since most nutrient table have a classname of "nutrition" im grabbing the via their className.我正在构建一个 chrome 扩展程序,它可以获取成分表并将其与数据集进行比较。因为大多数营养表都有一个类名“营养”,所以我通过它们的类名来获取。 This is what I got:这就是我得到的:

["\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"]

i need to loop thru this array and return it in this format:我需要遍历这个数组并以这种格式返回它: 在此处输入图像描述

I was thinking of using Regex to split out the doses (so words) and numbers?我在考虑使用 Regex 来拆分剂量(所以是单词)和数字?

Regex would be overkill for this.正则表达式对此来说太过分了。 You can simply split the strings and then map them into a format that's better for you to work with.您可以简单地拆分字符串,然后将它们 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);

This formats your input neatly into an array of objects with properties nutrient , per100 and per35 , which you can then use to generate your table's HTML from.这会将您的输入整齐地格式化为具有属性nutrientper100per35的对象数组,然后您可以使用这些对象从中生成表格的 HTML 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM